문제

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?

도움이 되었습니까?

해결책

Print out what it’s deleting and enable warnings to see what’s actually happening! =)

$GLOBALS contains GLOBALS. You unset it, which removes the actual global variable. If this were just pass-by-reference behaviour, you would get an empty array, not NULL.

다른 팁

This happens because its the expected behavior:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top