Forum Moderators: coopster

Message Too Old, No Replies

require() and include()

what Larry Ullman said in his book

         

yellow_nemo

5:06 pm on May 5, 2005 (gmt 0)

10+ Year Member



"Both functions work in the exact same way with only one significant difference. Regardless of where the require() function is within your script, it will always be called, even if it is the result of a conditional that is never true! The include() function, conversely, will only take effect if the function is called. Thus you should use require()if the file must be included and use include(), depending upon the circumstances at hand."

The paragraph is taken out of his "PHP for the world wide web" book.

I used the following code to do a testing

<?PHP
$a = 1;
if($a == 2) {
require("header.php");
}
?>

and based on what he said, header.php would show up. But nope, didn't work like that.

What do you think?

mooseh

5:46 pm on May 5, 2005 (gmt 0)

10+ Year Member



The key difference is that require will halt the processing of the page if the file isn't there - include just generates a warning.
However, the php manual does say that prior to PHP 4.0.2, require would always be called as described in that quote.

yellow_nemo

6:01 pm on May 5, 2005 (gmt 0)

10+ Year Member



Thanks mooseh. I didn't know about the prior to 4.0.2 thing. Now, I do.

yellow_nemo

10:19 pm on May 6, 2005 (gmt 0)

10+ Year Member



From php.net.......

Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.

Now that I've read the above paragraph a couple of times, I think I am confused.

However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.

So prior to 4.0.2, php will attempt to read the target file in require(), but wouldn't actually execute it? hmm..isn't that almost useless? it reads the file but not executing it? Isn't that the same as not reading the file in the first place?

coopster

12:48 pm on May 7, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Not really, it may just contain functions. They wouldn't be executed, but available if/when called.

And welcome to WebmasterWorld there, mooseh.