Function not behaving in the same way as normal code

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
Cut
Forum Commoner
Posts: 39
Joined: Sat Aug 23, 2008 8:01 pm

Function not behaving in the same way as normal code

Post 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.)
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

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

Post 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.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply