note 110314 added to function.unset
| From: | tigercat at aol dot com | Date: | Wed, 10 Oct 2012 07:55:57 +0000 |
| Subject: | note 110314 added to function.unset | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-191228@lists.php.net to get a copy of this message | ||
The combination of "global" and "unset" in functions can lead to some unexpected
results. This is because the "global" function creates a reference to a variable at the
time it's executed, so a variable can be deleted out from under a "global
$my_variable" declaration in a function. Accessing data that's been deleted with an
obsolete reference is usually a bad thing; in some languages it can generate a machine address
fault.
<?php
$my_global_var = "old data";
f1();
function f1() // example of invalid variable reference use
{
global $my_global_var; // creates reference to global variable
f2(); // recreates global variable, so reference is now invalid
// bad...
echo $my_global_var; // outputs "old data" (from invalid memory???)
// good...
global $my_global_var; // reestablish reference to new global variable
echo $my_global_var; // outputs "new data" as expected
}
function f2() // recreate global variable
{
unset($GLOBALS['my_global_var']); // this syntax works with all variable types including
arrays
global $my_global_var; // must do this after unset to access new global variable
$my_global_var = "new data";
}
?>
----
Server IP: 69.147.83.199
Probable Submitter: 72.201.124.170
----
Manual Page -- http://www.php.net/manual/en/function.unset.php
Edit -- https://master.php.net/note/edit/110314
Del: integrated -- https://master.php.net/note/delete/110314/integrated
Del: useless -- https://master.php.net/note/delete/110314/useless
Del: bad code -- https://master.php.net/note/delete/110314/bad+code
Del: spam -- https://master.php.net/note/delete/110314/spam
Del: non-english -- https://master.php.net/note/delete/110314/non-english
Del: in docs -- https://master.php.net/note/delete/110314/in+docs
Del: other reasons-- https://master.php.net/note/delete/110314
Reject -- https://master.php.net/note/reject/110314
Search -- https://master.php.net/manage/user-notes.php