Page 1 of 1

Function not behaving in the same way as normal code

Posted: Sat Aug 23, 2008 8:24 pm
by Cut
I had a function that looks like this:

Code: Select all

 
function error($message) {
 echo $message;
 require_once('footer.php');
 exit;
}
 
It did not work properly, so I cut it down to:

Code: Select all

 
function error($message) {
 echo $message;
}
 
...and then added the removed functionality directly to the code:

Code: Select all

 
   error("The style you selected does not appear to exist.");
   require_once('footer.php');
   exit;
 
This did work.

Can anyone explain why the behavior differed?

(If it matters, the "not working" thing was it not recognizing variables that are defined in the header. I use a very simple template system.)

Re: Function not behaving in the same way as normal code

Posted: Sat Aug 23, 2008 8:46 pm
by s.dot
footer.php if require_once()'d from within the function takes on the scope of the function
so it is a scope issue
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.