你怎么打破参考

How do you break a reference to a variable in PHP without destroying the variable itself?

I have written a PHP loop that stores a reference to objects in $GLOBALS['parent_variables'] and then destroy it at the end of the function.

The function is called in the loop. I assume I use:

unset($GLOBALS['parent_variables'])

Does that destroy the reference? Just to confirm...

I set the reference like this:

$GLOBALS['parent_variables'] = &$question->variables;

After:

$GLOBALS['parent_variables'] = &$question->variables;

Using:

unset($GLOBALS['parent_variables'])

... will break the reference -- as in set $parent_variables to null, while keeping $question->variables.

Using:

$GLOBALS['parent_variables'] = null

... will set both variables to null.

Example:

$foo = 'bar';

$GLOBALS['baz'] = &$foo;
unset($GLOBALS['baz']);
var_dump($GLOBALS['baz'], $foo);  # null, bar; undefined index notice for baz

$GLOBALS['baz'] = &$foo;
$GLOBALS['baz'] = null;
var_dump($GLOBALS['baz'], $foo);  # null, null; no notice (since baz is set)

Unsetting from the array does only remove the 'reference' and does not change the original object you copied from. Example:

<?php

$foo = new StdClass();
$foo->bar = "hello";
$_FAKE_GLOBAL_ARRAY = array();
$_FAKE_GLOBAL_ARRAY['foo'] = $foo->bar;
echo "array references ".$_FAKE_GLOBAL_ARRAY['foo'];
echo "<br>object contains ".$foo->bar;
unset($_FAKE_GLOBAL_ARRAY['foo']);
echo "<br>now array references ".(isset($_FAKE_GLOBAL_ARRAY['foo']) ? $_FAKE_GLOBAL_ARRAY['foo'] : " nothing");
echo "<br>now object contains ".$foo->bar;
?>

outputs

array references hello
object contains hello
now array references nothing
now object contains hello