question about include() and require() functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
greedyisg00d
Forum Commoner
Posts: 42
Joined: Thu Feb 12, 2009 2:48 am

question about include() and require() functions

Post 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
sujithtomy
Forum Commoner
Posts: 46
Joined: Tue Mar 24, 2009 4:43 am

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

Post 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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
Post Reply