require
and include
have the variations require_once
and include_once
. They prevent the script from loading a file multiple times.
I think I can safely assume, because the functions exist, that there would be cases where you would need the require
/include
function instead of the require_once
/include_once
one. But I cannot imagine a case like that. What would that be?
?> The require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.
Definition and UsageThe require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.
Probably the best example would be when giving output. If, say, you had a snippet of HTML that might appear more than once on various pages, you could put it into a separate file and include it as many times as you wanted.
Moreover, it's often unnecessary to use require_once
or include_once
. If the file will only be called once (e.g. in __autoload
) then the simple functions have less overhead, because PHP doesn't need to keep track of whether the file has been included before.
One may want to use require_once instead of require if you want to have a variable or constant defined only once. This is helpful for making reusable classes in a very large code base that manages dependencies rapidly. Lets say I have a file A that needs a file B but I already include file C that included file B. Since file B was already included, the program does not have to evaluate that code again to properly evaluate file A. This is a case where you may want to include the file only once.
It helps with managing your dependencies
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With