4

I came across some weird behavior in PHP:

function f($var) { // not using references
    foreach ($var as $k => $v) {
        unset($var[$k]); // shouldn't this unset from a copy?!
    }
}

print '<pre>';
var_dump($GLOBALS); // array
f($GLOBALS);
var_dump($GLOBALS); // null?!

http://3v4l.org/dQmQN

Anybody know why this is happening?

4

2 回答 2

3

打印出它正在删除的内容并启用警告以查看实际发生的情况!=)

$GLOBALS包含GLOBALS. 你unset它,它删除了实际的全局变量。如果这只是按引用传递的行为,您将得到一个空数组,而不是NULL.

于 2013-05-09T14:59:19.787 回答
1

发生这种情况是因为它的预期行为

这是一个“超全局”或自动全局变量。这仅仅意味着它在整个脚本的所有范围内都可用。没有必要做全局 $variable; 在函数或方法中访问它。

于 2013-05-09T14:55:14.677 回答