Page 1 of 1

Any difference between require() in PHP and include in C?

Posted: Tue Nov 15, 2005 7:50 pm
by kknight
Are they doing the same thing?
Is require() in PHP equal to expanding the required PHP script at the require() location?
Thanks.

Posted: Tue Nov 15, 2005 8:32 pm
by RobertPaul
From TFM:
require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error.

Posted: Tue Nov 15, 2005 8:33 pm
by trukfixer
pretty much, yes..

require()
require_once() (better)
include()
include_once() (my preference)

All do the same thing in php , basically "insert the contents of teh file in this point in the script"

require and require_once will spit out a fatal error and kill script execution if teh file cannot be read or is missing, while include and include_once only issue a warning but continue with the rest of script execution ..

I prefer the use of include_once myself, as it will prevent re-loading an already loaded or included file.. (it happens sometimes in larger scripts)

Posted: Wed Nov 16, 2005 12:53 am
by kknight
Thanks for your reply.
But, I think require() is not like "insert the contents of the file in this point in the script".
For example, there are two files: a.php and b.php

a.php has the following content:
<?
require 'b.php';
?>

b.php has the following content:
<?
$a=1;
?>

If we only treat require() as "insert the contents of the file in this point in the script".
The resulting a.php will be something like this:
<?
<?
$a=1;
?>
?>

Is this a valid php script?
In this sense, require() is not the same as the #include in C language. Any thoughts?
trukfixer wrote:pretty much, yes..

require()
require_once() (better)
include()
include_once() (my preference)

All do the same thing in php , basically "insert the contents of teh file in this point in the script"

require and require_once will spit out a fatal error and kill script execution if teh file cannot be read or is missing, while include and include_once only issue a warning but continue with the rest of script execution ..

I prefer the use of include_once myself, as it will prevent re-loading an already loaded or included file.. (it happens sometimes in larger scripts)

Posted: Wed Nov 16, 2005 5:58 am
by Chris Corbyn
#include <file> //OK less so with the <>
and
#include "file"

are *similar* to include() require() etc in php yes but the behaviour... as you've noticed, is not exactly the same.

PHP will parse the contents of the file it is including during script execution.... rather than simply place the contents inline.

It's simply a way to reuse code and re-factor into smaller parts.

Each include(), include_once(), require() and require_once() have their own little diffrerences too.