Re: using return in include files

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Aaron Axelsen wrote:
> I'm trying to figure out what the desired behavior is of using the
> return function to bail out of an include page.
> 
> I did some testing, and this is what I concluded.
> 
> First, I created the following file:
> 
> <?php
> if (defined('TEST_LOADED')) {
>         return;
> }
> define('TEST_LOADED',true);
> echo "blah blah blah blah<br/>";
> ?>
> 
> I then called it as follows:
> include('test.php');
> include('test.php');
> include('test.php');
> 
> The output is:
> blah blah blah blah
> 
> Second, I changed the test.php file to be the following:
> 
> <?php
> if (defined('TEST_LOADED')) {
>         return;
> }
> define('TEST_LOADED',true);
> echo "blah blah blah blah<br/>";
> 
> function myFunc($test) {
> 
> }
> ?>
> 
> When I load the page now, it throws the following error: PHP Fatal
> error: Cannot redeclare myfunc()
> 
> It appears that if there are functions in the include page that you
> can't use return to bail out.  What is the desired functionality in this
> case?  Is this a bug in how php handles it? or was return never designed
> to be used this way?
> 
> Any thoughts are appreciated.

Hi Aaron,

Unfortunately, the only way you can prevent the parse error is to use a
conditional function, return won't cut is, as the file is re-parsed
every time you include it, and all classes/functions are re-parsed
before the run-time if() is processed.

<?php
if (!function_exists('myFunc')) {
function myFunc($test) {
}
}
?>

This will work, but does slow down opcode caches and introduce potential
instability with them, as the added complexity is very unfriendly to
optimization.

Of course, you are much better off taking advantage of the
include_once[1] language construct, or separating your
need-to-be-included-many-times file from any function or class definitions.

Greg

http://www.php.net/include_once

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux