MaximPro MaximPro - 3 months ago 13
PHP Question

global vs $GLOBALS

I have this code

/// Example 1
$str = "Simple text";
$a = function()
{
global $str;
$str = "edited";
};
$a();
echo $str."\n"; /// edited

/// Example 2
$str = "Simple text";
$a = function()
{
$GLOBALS["str"] = "edited";
};
$a();
echo $str."\n"; /// edited

/// Example 3
$str = "Simple text";
$temp = "";
$a = function()
{
$GLOBALS["temp"] = &$GLOBALS["str"];
};
$a();
echo "[".$str."] [".$temp."]\n"; /// [Simple text] [Simple text]

/// Example 4
$str = "Simple text";
$temp = "";
$a = function()
{
global $str, $temp;
$temp = &$str;
};
$a();
echo "[".$str."] [".$temp."]\n"; /// [Simple text] []


The first example displays as well as the expected change in the value of the second example of the same thing ... it would seem there is no difference, go ahead! In the third example, the function we make a hard link to superglobal array displays as expected the same word, and now look at a fourth example, and ... I'm not in a stupor, he links and displays only the variable
$str
, and the variable
$temp
reserves empty, why?

Answer

It is greatly explained in docs: http://php.net/variables.scope and http://php.net/manual/language.references.spot.php

global $a;

Is a shortcut to:

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

So lets expand your last example:

$a = function()
{
    $str = &$GLOBALS['str'];
    $temp = &$GLOBALS['temp'];
    $temp = &$str;  // okay, but $temp is still the local variable 
};

I think everything works as expected