note 71541 deleted from language.variables.scope by bjori
| From: | bjori@php.net | Date: | Tue, 05 Dec 2006 15:05:02 +0000 |
| Subject: | note 71541 deleted from language.variables.scope by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-120301@lists.php.net to get a copy of this message | ||
Note Submitter: mark (at) dreamjunky dot com
Reason: in docs
----
Something to watch out for if you ever require/include files inside a function:
== file1.php ========
<?php
$a = 3;
$b = 2;
function add_them() {
global $a, $b;
echo $a + $b;
}
?>
== file2.php ========
<?php
function do_it() {
require ('file1.php');
add_them();
}
?>
If you run file2.php, you would NOT get 5. Here's why. In file1.php, $a and $b are declared
in the scope global to that file. However file2.php requires file1.php inside a function do_it(),
so the variables are actually within the scope of the do_it() function.
When add_them() is called and PHP encounters the line global $a, $b, there aren't any $a and $b
variables in the global scope to import. Thus $a and $b are empty and $a + $b is 0.
Best way to avoid this would be to avoid using globals, or not requiring/including files inside
functions.