Online Shopping : Computers : Programming : Languages : PHP : kms : Functions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to
Did You Find This Entry Useful?

66 of 79 people (84%) answered Yes
Recently 7 of 10 people (70%) answered Yes


What is the difference between require() and include()?

Dec 1st, 2008 06:32
forum net tr, games games, Philip Olson, Nathan Wallace, Zeev Suraski

As of PHP 4.0.2 and later, require() can be described, in PHP psuedo-
code as :
  if (include($filename) == FAILURE) {
      print "Fatal error:  Unable to require $filename";
Essentially this means that if it fails, the script WILL end 
In PHP 3.0.x, and PHP 4.0 versions prior to PHP 4.0.3, require() had 
another implementation difference - it was always, under all 
circumstances, performed exactly once.  For instance :
  for ($i=0; $i<100; $i++) { require('foo.php'); }
Would have been converted to :
  for ($i=0; $i<100; $i++) { ...contents of foo.php... }
And then executed, getting the contents of foo.php iterated a hundred 
times. Another example is as follows :
  if (false) { require("foo.php"); }
Would *still* read the contents of foo.php, turning it to :
  if (false) { ...contents of foo.php... }
And only then PHP would figure out that it doesn't even have to 
this code.
As of PHP 4.0.3, the implementation of require() no longer behaves 
way, and processes the file 'just in time'.  That means that in the 
example, the file will be processed a hundred times, and in the 2nd 
example, it won't be processed at all.  That's the way include() 
behaves (in all versions of PHP) as well.
Other than that, include() and require() have no difference 
they both behave the same with URLs, safe mode, and anything you can 
think of.
So, it still makes perfect sense to use require() when it'll make no 
sense for your script to continue if the file is not found, which is 
the case, more often than not.
The bulk of this was initially posted to php-general by Zeev and can 
seen here :
  Topic : Require() vs Include()
And for good measure :