note 71541 added to language.variables.scope
| From: | (at) | Date: | Tue, 05 Dec 2006 03:17:57 +0000 |
| Subject: | note 71541 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120288@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 64.71.164.2
Probable Submitter: 68.202.68.182
----
Manual Page -- http://www.php.net/manual/en/language.variables.scope.php
Edit -- https://master.php.net/note/edit/71541
Del: integrated -- https://master.php.net/note/delete/71541/integrated
Del: useless -- https://master.php.net/note/delete/71541/useless
Del: bad code -- https://master.php.net/note/delete/71541/bad+code
Del: spam -- https://master.php.net/note/delete/71541/spam
Del: non-english -- https://master.php.net/note/delete/71541/non-english
Del: in docs -- https://master.php.net/note/delete/71541/in+docs
Del: other reasons-- https://master.php.net/note/delete/71541
Reject -- https://master.php.net/note/reject/71541
Search -- https://master.php.net/manage/user-notes.php