PHP programmers regularly use the functions (or more appropriately language construct) include(), include_once(), require() and require_once(), to insert useful codes written in other files, in the flow of execution. Although these constructs are used quite interchangeably, there are actually significant differences among them, specially when you are building well designed applications. Although these differences are very well defined in PHP manual, I've noticed many programmers don't really consider them while coding. I hope this tutorial will help them towards a better coding practice.
The difference between include() vs. include_once() or require() vs. require_once() is obvious. include() and require() allow you to insert a file multiple times within a single execution lifetime. On the other hand, include_once() and require_once() make sure one file is inserted only once in a single execution lifetime, even if your CODE calls them multiple times.
Ironically, a little less obvious and in fact more significant difference is, between include() vs. require() or include_once() vs. require_once(). Even though PHP's naming of these constructs are almost perfect according to their functionality, many PHP programmers, specially the beginners seem to avoid the significant difference.
As the name suggests, with include(), you simply include other files in the flow of execution. On the other hand, when you use require(), you not only include the file in the flow of execution, but also you tell PHP that the execution cannot be proceeded without this file. In more technical terms:
If PHP interpreter fails to include a file in response to a call of include() or include_once(), a Warning in generated and execution continues without that file. Where as, failure to include a file called by require() or require_once() generates a Fatal Error and execution stops there.
So in a normal scenario, where you want the execution to go on and show users the output, even if a file is accidentally missing (or perhaps it's the part of the Programming Logic), use include() or include_once().
On the other hand, in case of FrameWork, CMS or a complex PHP application coding, always use require() or require_once() to include a key file to the flow of execution. This will help avoid compromising your application's security and integrity, just in-case one key file is accidentally missing. Then use error_reporting(0) to suppress all the errors and proper Error Handler to show appropriate data.
For more information see PHP manual or this online resource.
by Fayaz Ahmed
Leave a Reply