Is it possible to set a global PHP variable to a pointer?

Why can't PHP specify a 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 ?> 
+6
source share
3 answers

FROM PHP Guide :

A warning

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

...

Think of global $ var; as a shortcut to $ var = & $ GLOBALS ['variable'] ;. Thus, assigning another reference to $ var only changes the local variable 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 Which Links Are Not and Return Links

+4
source

PHP does not use pointers. The manual explains which links are there, to do and not to do. Your example is specifically addressed 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, as described in 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 ?> 
0
source

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

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

The link is visible only inside myfunc ().

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

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

0
source

All Articles