Jump to content

unset() doesnt work on global variables?


arianhojat

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?)

<?php
$x = 10;

echo "\nBefore function ". $x;

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

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

unset($x);
echo "\nUnset Inside function ". $x;

}
change();
echo "\nOutside function ". $x;

?>
Link to comment
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:
"
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.