RE: gloabl & reference behavior question?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 20 July 2005 23:40, Surendra Singhi wrote:

> Hello,
> 
> (1)
> When I try this code:
> <?php
> 
>     $var_global =" stuff";
>     function f1() {
>       global $var_global;

This is equivalent to creating a $var_global which is local to the function,
and making it be a reference to the global $var_global -- effectively:

    $var_global = &$GLOBALS['var_global'];


>       $var_local = array(1,2);
>       $var_global =& $var_local;

But this assigns a new reference to $var_local to the (local) $var_global,
thus breaking the reference to the (global) $var_global -- so the (global)
$var_global isn't changed by this assignment.

>     }

Thus, when the function returns, the (local) $var_global disappears, and the
(global) $var_global comes back into scope with its value unchanged.

>     f1();
>     print_r($var_global);
> > 
> I get the output:
> 
> stuff
> 
> where as I was expecting junk value or null.
> 
> 
> My question is that, because the array is created locally and we
> pass it by reference (without copying) so on the exit of
> function, its value
> is lost, but how does the global variable gets back its old value?

See description above.

> Is it something which is not defined by the PHP language
> reference and is
> implementation specific?

No this is described in the manual at
http://php.net/global#language.variables.scope.references

To do what you're trying to do, you should make use of the $GLOBALS
superglobal:

    $GLOBALS['var_global'] = &$var_local;

But that seems very dodgy -- and, since $var_local disappears when the
function returns anyway, why not just:

    $GLOBALS['var_global'] = array(1,2);

Overall, I'd be somewhat suspicious about what your function is trying to
do, as the whole approach seems rather convoluted to me.

Cheers!

Mike

---------------------------------------------------------------------
Mike Ford,  Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Headingley Campus, LEEDS,  LS6 3QS,  United Kingdom
Email: m.ford@xxxxxxxxxxxxxx
Tel: +44 113 283 2600 extn 4730      Fax:  +44 113 283 3211 


To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux