tags:

views:

43

answers:

3

If I have this:

require_once('myfile.php');

then later:

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?

+7  A: 

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.

thephpdeveloper
A: 

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.

A: 

It's worth saying that using the require_once() or include_once() rather than just require() or include() does add some overhead to your program -- PHP needs to keep a lookup table of all the _once() calls, so it knows not to include them again, plus it needs to scan that lookup table each time you do a _once() call.

In a small app, this really doesn't make much difference... but in a small app, you probably don't have much need to use _once() too much anyway.

In a large app, with a lot of files to include, it can make a noticable difference to performance if you can minimise use of the _once() functions.

The message is: don't use _once() unless you actually need it (ie the file might have already been included, but you don't know for sure).

Spudley