Page 1 of 1

question about include() and require() functions

Posted: Thu Mar 26, 2009 10:29 pm
by greedyisg00d
I already read some information about these two functions including the php manual but I am still confused on when and how to use it. Another is the difference between include_once() and require_once(). Therefore, which is more preferable or standard to use nowadays?

Thanks

Re: question about include() and require() functions

Posted: Thu Mar 26, 2009 11:12 pm
by sujithtomy
Hello,

require and include is almost the same. The difference is that if include fails, it throws a warning, if require fails, it shows a fatal error.

if any files which is must for application (say config files) use require_once. but require_once will check for physical existence of file, it is bit slower than include_once.

require_once and include_once works the same way, but here you can be sure that the file you include will ne included only one time, even if you include/require it twice or more. This make sense including files with functions or classes.

Re: question about include() and require() functions

Posted: Thu Mar 26, 2009 11:16 pm
by requinix
include - file doesn't have classes or functions defined inside; it's okay if it doesn't exist
require - file doesn't have classes or functions defined inside; not okay if it doesn't exist
include_once - file has classes or functions defined inside; it's okay if it doesn't exist
require_once - file has classes or functions defined inside; not okay if it doesn't exist

I interpret "it's okay if it doesn't exist" to mean that if the file cannot be found then it's not the end of the world and your application can (should be able to) handle it.
"Not okay" means that without this file your script can't work.

Code: Select all

<?php
 
require_once "database.php"; // necessary file to continue, has functions
 
$header = db_find_template("the header with the funny logo");
if ((include $header) != 1) { // try to use it if possible, no functions or classes
    require "default_header.php"; // just in case the first wasn't found use this
}
 
// ...
 
$footer = db_find_template("the footer with the normal logo");
if ((include $footer) != 1) {
    require "default_footer.php";
}
 
?>
I've never really needed to use include_once.