我有这个代码
/// 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] []第一个示例显示了同一事物的第二个示例的值的预期变化……看起来没有什么区别,继续吧!在第三个示例中,我们硬链接到超全局数组的函数如预期的那样显示相同的单词,现在看第四个示例,并且...我并没有昏迷,他只链接和显示变量$str,而变量$temp保留为空,为什么?
发布于 2016-09-11 05:13:19
文档http://php.net/variables.scope和http://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
};我想一切都如我所愿。
https://stackoverflow.com/questions/39430556
复制相似问题