全球对抗$ GLOBALS

时间:2016-09-10 21:04:51

标签: php

我有这段代码

/// 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] []

显示第一个示例以及同一事物的第二个示例的值的预期变化......看起来没有区别,请继续!在第三个例子中,我们与超全局数组建立硬链接的函数按预期显示相同的单词,现在看第四个例子,并且...我不是在昏迷中,他链接并只显示变量{ {1}},变量$str保留为空,为什么?

1 个答案:

答案 0 :(得分:2)

在文档中对此进行了详细解释:http://php.net/variables.scopehttp://php.net/manual/language.references.spot.php

global $a;

是一个快捷方式:

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

所以让我们展开你的最后一个例子:

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

我认为一切都按预期工作

相关问题