RE: [PHP] Require() vs Include()

From: Date: Tue, 14 Nov 2000 06:14:46 +0000
Subject: RE: [PHP] Require() vs Include()
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-25134@lists.php.net to get a copy of this message
Mark Peoples writes: > Hi Maxim, > Suppose you have this: > > --file1.php-- > <?php print("\nin file1.php"); ?> > > --file2.php-- > <?php print("\nin file2.php"); ?> > > > Now, suppose you want to include certain files, based on conditions: > > --test.php-- > if($myCatVioletHasBlackFur == "no") > require(file1.php); > if($myCatVioletHasBlackFur == "yes") > include(file2.php); > > Well, my cat, Violet <g>, has black fur, so the 2nd condition is valid, the > 1st is false. However, require() is executed regardless, so, the output of > test.php is: > > in file1.php > in file2.php No offense, but this is incorrect. The above would do what you say, but only in PHP 3, and not for the reason you think. From the manual (http://www.php.net/manual/function.include.php): Because include() is a special language construct, you must enclose it within a statement block if it is inside a conditional block. /* This is WRONG and will not work as desired. */ if ($condition) include($file); else include($other); /* This is CORRECT. */ if ($condition) { include($file); } else { include($other); } (Yes, it's about include(), but also applies to require()). In PHP 3, you *need* those { } there to get around the fact that include() and require() are not functions. If you treat them like functions, they'll just act weird, doing what you want one minute and then turning and biting you the next. In PHP 4, the above would give the result: in file2.php Even though the require() is executed, execution must still pass through it for the require()d code to be executed. So if execution never hits the inside of the if() block, although the file has been require()d, its *contents* never get executed. > So, what if I change test.php to: > > --test.php-- > if($myCatVioletHasBlackFur == "no") > include(file1.php); > if($myCatVioletHasBlackFur == "yes") > include(file2.php); > > > Well, Violet still has black fur, so, the output is: > > in file2.php > > > Hope this helps. =) > > > marco -- +----------------------------------------------------------------+ |Torben Wilson <torben@php.net> Netmill iTech| |http://www.coastnet.com/~torben http://www.netmill.fi| |Ph: 1 250 383-9735 torben@netmill.fi| +----------------------------------------------------------------+

« previous php.general (#25134) next »