Dont unset that variable you need globally - Page 2

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Re: Re: Dont unset that variable you need globally

"" wrote:
 > > Dont make my mistake. It is costly.
 > >
 > > Say you have defined a variable $var in your main script.
 > >
 > > Now in a function you access it using:
 > > global $var;
 > >
 > > But you want to set it to null inside the function.
 > > DO:   $var = null;
 > > DONT DO:  unset($var);
 > >
 > > Why?  Because the 2nd way removes the variable from the name
 > space,
 > > and it is no longer globally available. Cost me 10 hours....
 > That's odd. The manual seems to disagree:
 > "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.
 > <?php
 > function destroy_foo()
 > {
 >    global $foo;
 >    unset($foo);
 > }
 > $foo = 'bar';
 > destroy_foo();
 > echo $foo; // prints "bar"
 > ?>"
 > - from
 > Now I don't know what to believe..
 > --  
 > Welcome to Usenet! Please leave tolerance, understanding
 > and intelligence at the door. They aren't welcome here.
 > eternal piste erection miuku gmail piste com


That was my point, sorry for causing confusion.  Thanks for reference.

So unset does not work inside a function for global vars- it only
destroys local var.

The workaround is to say  
$var = null;
inside functions.

This is to my counter-intuitive, and unless you read the manual, one
would not know.

Posted using the interface, at author's request
Articles individually checked for conformance to usenet standards
Topic URL:
Visit Topic URL to contact author (reg. req'd).  Report abuse:

Re: Don’t unset that variable you need globally

Quoted text here. Click to load it

 Although the variable remains set that way - it's just null.

 To get rid of it completely: unset($GLOBALS['var']);

< Space: disk usage analysis tool

Re: Don?t unset that variable you need globally

Quoted text here. Click to load it

$DEITY forbid that anyone should read the manual!

But one could consider the global keyword to be extremely evil (changing
scopes of variables is extremly yuck), use the superglobal $GLOBALS
instead (note the unintuitive missing '_').

FUP to comp.lang.php

Site Timeline