class A {
public $a;
public function foo() {
$b = array("a", "b");
$this->a = &$b;
}
}
会发生什么?
$b
array
的pointer
,当函数foo()
退出时,$b
消失而数组仍然存在?
如果数组也消失了,$a
将失去对它的引用。
谁能为我解释一下?
我想你的意思是这样的:
是的,你可以!在这里,您将array $b
指定为对$a
的引用并更改$b
。然后你输出$a
它与更改后的$b
相同!
<?php
class A {
public $a;
function foo() {
$b = array("a", "b");
$this->a = &$b;
$b[] = "c";
print_r($b);
unset($b);
print_r($b);
print_r($this->a);
}
function foo2() {
print_r($this->a);
}
}
$test = new A();
$test->foo();
$test->foo2();
?>
输出:
Array ( [0] => a [1] => b [2] => c ) //$b
Notice: Undefined variable: b in C:'xampp'htdocs'Testing'index.php on line 27 //after unset $b
Array ( [0] => a [1] => b [2] => c ) //$a from the function foo
Array ( [0] => a [1] => b [2] => c ) //$a from the function foo2
评论后更新:
(带全局变量(
<?php
global $c;
$c = 42;
$d = &$c;
$c = 2;
unset($c);
echo $d;
?>
输出:
2