Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you want to include/require multiple times?

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?

like image 517
Joren Avatar asked Nov 02 '13 21:11

Joren


People also ask

What is the difference between require and require once?

?> 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.

How do you use require once?

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.


2 Answers

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.

like image 176
lonesomeday Avatar answered Oct 22 '22 05:10

lonesomeday


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

like image 33
Hoodlum Avatar answered Oct 22 '22 06:10

Hoodlum