6

Why can't PHP keep a pointed value as a global variable?

<?php
   $a = array();
   $a[] = 'works';
   function myfunc () {
      global $a, $b ,$c;
      $b = $a[0];
      $c = &$a[0];
   }
   myfunc();
   echo '  $b '.$b; //works
   echo ', $c '.$c; //fails
?>
Tepken Vannkorn
  • 9,380
  • 14
  • 55
  • 84
kurma
  • 67
  • 3

3 Answers3

4

FROM PHP Manual:

Warning

If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the $GLOBALS array.

...

Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus assigning another reference to $var only changes the local variable's reference.

<?php
$a=array();
$a[]='works';
function myfunc () {
global $a, $b ,$c;
$b= $a[0];
$c=&$a[0];
$GLOBALS['d'] = &$a[0];
}
myfunc();
echo '  $b '.$b."<br>"; //works
echo ', $c '.$c."<br>"; //fails
echo ', $d '.$d."<br>"; //works
?>

For more information see: What References Are Not and Returning References

Community
  • 1
  • 1
0

PHP doesn't use pointers. The manual explains what exactly references are, do and do not do. Your example is addressed specificly here: http://www.php.net/manual/en/language.references.whatdo.php To achieve what you are trying to do, you must resort to the $GLOBALS array, like so, as explained by the manual:

<?php
$a=array();
$a[]='works';
function myfunc () {
global $a, $b ,$c;
$b= $a[0];
$GLOBALS["c"] = &$a[0];
}
myfunc();
echo '  $b '.$b; //works
echo ', $c '.$c; //works
?>
Ultimater
  • 4,309
  • 2
  • 26
  • 40
0

In myfunc() you use global $a, $b, $c.

Then you assign $c =& $a[0]

The reference is only visible inside myfunc().

Source: http://www.php.net/manual/en/language.references.whatdo.php

"Think about global $var; as a shortcut to $var =& $GLOBALS['var'];. Thus assigning another reference to $var only changes the local variable's reference."