昨天我和我的一个朋友正在经历静态课程,并且是实例课程;然后突然发生了一些奇怪的行为。
<?php
class NumberContainerO {
public $_number;
public function __construct($number) {
$this->_number = $number;
}
}
$list = array();
$n = new NumberContainerO(1);
$list[] = &$n->_number;
$n = new NumberContainerO(2);
$list[] = &$n->_number;
$n = new NumberContainerO(3);
$list[] = &$n->_number;
var_dump($list);
?>
<?php
class NumberContainer {
public static $_number;
public static function __Add($number) {
self::$_number = $number;
}
}
$list = array();
NumberContainer::__Add(1);
$list[] = &NumberContainer::$_number;
NumberContainer::__Add(2);
$list[] = &NumberContainer::$_number;
NumberContainer::__Add(3);
$list[] = &NumberContainer::$_number;
var_dump($list);
?>
输出
array(3){ [0] =&GT; INT(1) [1] =&GT; INT(2) [2] =&GT; &安培; INT(3) } array(3){ [0] =&GT; &安培; INT(3) [1] =&GT; &安培; INT(3) [2] =&GT; &安培; INT(3) }
为什么int(1)和int(2)没有通过引用传递?
答案 0 :(得分:2)
执行$n = new NumberContainerO(2);
(和$n = new NumberContainerO(3);
)后,您将取消之前的$n->_number
,从而销毁参考号。然后,数组元素将成为标准的非引用值。