Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between require and include with php? [duplicate]

Tags:

include

php

I want to know when I should use include or require and what's the advantage of each one.

like image 348
Bigballs Avatar asked Feb 27 '09 19:02

Bigballs


4 Answers

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.

like image 59
Paolo Bergantino Avatar answered Oct 20 '22 00:10

Paolo Bergantino


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.

like image 22
Alan Storm Avatar answered Oct 19 '22 22:10

Alan Storm


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

like image 31
robmerica Avatar answered Oct 19 '22 22:10

robmerica


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.

like image 33
ceejayoz Avatar answered Oct 19 '22 23:10

ceejayoz