I know the basic usage of PHP require, require once, include and include once. But I am confused about when I should use them.
Example: I have 3 files, eg: settings.php, database.php, and index.php.
In database.php file, i wrote:
require_once 'settings.php';
and then in index.php, i wrote:
require_once 'settings.php'; require_once 'database.php';
so I load settings.php two times, is this okay? Any tips using these functions?
Advertisement
Answer
includeincludes a file and throws a warning if the file was not found.requireincludes a file and throws a fatal error if the file was not found.include_onceandrequire_oncedo the same thing, but only if the file was not already loaded.
However, the need for one of the _once functions is usually a sign of bad design. You should build your scripts in a way that clearly defines what gets included where.
Choose one place for settings.php to get included – probably index.php. There should be no need to additionally include it in database.php.