I want to know when I should use include
or require
and what's the advantage of each one.
require
requires, include
includes.
According to the manual:
require() is identical to include() except upon failure it will produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.
As others have said, if "require" doesn't find the file it's looking for, execution will halt. If include doesn't file the file it's looking for, execution will continue.
In general, require should be used when importing code/class/function libraries. If you attempt to call a function, instantiate a class, etc. and the definitions aren't there, Bad Things will happen. Therefore, you require php to include your file, and if it can't, you stop.
Use include when you're using PHP to output content or otherwise execute code that, if it doesn't run, won't necessarily destroy later code. The classic example of this is implementing a View in a Model/View/Controller framework. Nothing new should be defined in a view, nor should it change application state. Therefore, it's ok to use include, because a failure won't break other things happening in the application.
One small tangent. There's a lot of conflicting information and mis-information out there regarding performance of include vs. require vs. require_once vs. include_once. They perform radically different under different situations/use-cases. This is one of those places where you really need to benchmark the difference in your own application.
The difference is this: include will not fail if it cannot find the resource, require will. Honestly, it's kind of silly that include exists at all, because if you are attempting to load a resource you are pretty much counting on it being there. If you are going to use anything, I would recommend using require_once always, that way you don't run into collisions (ie, if another script is requiring the same file) and your code always works as intended because you know the resources you are including are there (otherwise it is failing).
If a file is optional, include it. For example, you might have a file 'breaking-news.txt' that gets created when there's breaking news, but doesn't exist when there's none. It could be included without the script breaking if there's no breaking news.
If the file is required for the rest of the script to function properly, require it.
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