Jump to content


This topic is now archived and is closed to further replies.


unset() doesnt work on global variables?

Recommended Posts

I use a variable $x inside my function. the $x that it is refering to is the global one, as it is declared by global keyword. but unsetting a global variable seem to not unset the variable outside of the function. is this true?

here is an example. prints out:

Before function 10
Inside function 10
Change Inside function 20
Unset Inside function (<<<<-PHP Notice:  Undefined variable)
Outside function 20 (Should be undefined here, right?)

$x = 10;

echo "\nBefore function ". $x;

function change(){
global $x;
echo "\nInside function ". $x;

$x = 20;
echo "\nChange Inside function ". $x;

echo "\nUnset Inside function ". $x;

echo "\nOutside function ". $x;


Share this post

Link to post
Share on other sites
I suggest you read the manual again


Share this post

Link to post
Share on other sites
doh i was a little woozy at the time reading it, so i glanced at the following lines and read right by them heh.
"If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
If you would like to unset() a global variable inside of a function, you can use the $GLOBALS array to do so:

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.