Tuesday, March 17, 2009

include, require, include_once, require_once

When it comes to dividing and ruling your code, PHP has a confusing amount of standard functions to do the job. Take include() for example. It works fine so why make the other copycats?
To figure that one out there's no better place to go to than the PHP.net. Once there search for the next big thing after include() - require(). And there you have it, the difference between include() and require() is the way the two handle their inability to load the specified file. Upon failing include() would only output a warning, whereas require() would result in a fatal error. 
Therefore, if it is crucial to execute a certain script - require() it, on the other hand if you can do without that script if PHP will fail to load it - include() it.

That being said we can move on to incude_once() and require_once() functions. The sole purpose of adding _once to require and include is to make sure they won't accidently repeat themselves. And in case the PHP interpreter will run in, let's say, require_once('myfile.php') two, three or more times it will simply ignore them, executing the script myfile.php only once. This can be very usefull when your code becomes too big and complex and you don't want PHP to go through the same scripts several times.

There's also the performance issue. When running _once() functions PHP has to check whether the file has already been included or not, but that only becomes an issue when you have hundreds of those.  So if you're interested you can find some controversial benchmark results by Googling something like php include require benchmark or include vs require vs include_once vs require once

No comments:

Post a Comment