Will require_once and include_once together include the file twice?
If I have this:
require_once('myfile.php');
then later:
开发者_JS百科include_once('myfile.php');
Will the file get included again or just the once?
Also what is the difference between the two? Require causes an error on failure and include tries to recover? any other differences?
If the file is included, it is included.
requice_once()
works exactly like include_once()
, except that it kills the script when the script to include is not found.
Therefore in your example, the script is included once.
Conceptually: Include does what it says on the tin: it includes the code of 'myfile.php' in the code of the current file. Require is more like an import statement in other programming languages.
The _once suffix means that PHP avoids inlcuding/requiring the file if it is already available to the current script via a previous include/require statement or recursively via include/require statements in other imported scripts.
Will the file get included again or just the once?
myfile.php
is just included the once.
require_once 'myfile.php'; //included
include_once 'myfile.php'; // not included
What is the difference between the two?
include
andinclude_once
will both emit a warning if it cannot find a file.require
andrequire
will emit a fatal error if it cannot find a file.
The difference between include_once
and require
is that when they cannot find the file include_once
will emit a warning and require
will emit a fatal error.
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue. [http://php.net/manual/en/function.require.php]
Require causes an error on failure and include tries to recover? any other differences?
include
allows you to recover yes, a failed require
statement is always ending one way, a try
catch
cant even save your script.
Its worth pointing out what would happen if other combinations of the four file evaluation statments (include
, include_once
,require
and require
) were used.
If the file were found
include
and require
will always include the file regardless of whether you have previously used require
,include
, require
or include_once
with the same file.
include_once 'myfile.php'; //included
include 'myfile.php'; //always included
require 'myfile.php'; //always included
require_once 'myfile.php'; // not included, prevously included via [function.include_once], [function.include] and [function.require]
include_once
and require
will only include the file if it has not been previously included using a require
,include
, require
or include_once
statement.
require 'myfile.php'; //always included
include_once 'myfile.php'; // not included, prevously included via [function.require]
精彩评论