> -----Original Message----- > From: Martin Peck [mailto:[EMAIL PROTECTED] > Sent: 28 July 2003 15:33 > > The following code illustrates a problem I've got with > references (running > on PHP 4.3.2). Can anyone explain it for me? Thanks in > advance for any > assistance! > Martin > > <?php > > $globalvariable = 0; > $one = 1; > > //want to set up $globalvariable as a reference to $one > setglobal($one); > > echo $globalvariable; //prints 0, not 1 > > function setglobal(&$one) > { > global $globalvariable;
PHP actually handles this by executing the equivalent of: $globalvariable = &$GLOBALS['globalvariable']; -- that is, it creates a $globalvariable *which is local to the function* and makes it be a reference to the global-scope variable of the same name. > $globalvariable =& $one; This says to make the local $globalvariable be a reference to $one, *not* to assign the value of $one to the variable referred to by $globalvariable -- so you've just overwritten the reference to the global $globalvariable with a reference to $one! This means that you now have no way to refer to the global-scope $globalvariable from within this function. There are two key concepts here, which often seem to get overlooked: (1) When you assign a reference to a variable which already contains a reference, the action is to *replace* the existing reference with the new one (*not* to assign the new reference through the existing reference). (2) In a function, the global and static mechanisms are both handles by defining variables local to the function which are *references* to the appropriate location (thus, you *cannot* assign references to global or static variables). This is explained, albeit in a rather oblique way, on the manual page at http://www.php.net/manual/en/language.variables.scope.php Cheers! Mike --------------------------------------------------------------------- Mike Ford, Electronic Information Services Adviser, Learning Support Services, Learning & Information Services, JG125, James Graham Building, Leeds Metropolitan University, Beckett Park, LEEDS, LS6 3QS, United Kingdom Email: [EMAIL PROTECTED] Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php