当我期望"44"时,它的输出是"24"。
class some_class {
public $array = array();
public function construct() {
$this->array[5] = 4;
}
public function something() {
// $this->array at this point is empty, why?
echo (isset($this->array[5])) ? $this->array[5] : 2;
$this->array[5] = 4;
// Here, $this->array holds the value 4 in the key 5 correctly
echo (isset($this->array[5])) ? $this->array[5] : 2;
}
}
$some_object = new some_class();
$some_object->something();
知道为什么我的期望被打破了吗?
你的构造函数没有触发它需要被调用:
public function __construct(){
// constructor
}
你的问题基本上归结为你在something()
开头的那一行,问:
$this->数组此时为空,为什么?
这是因为PHP构造函数需要命名为__construct
,而您的构造函数只需命名为construct
。
您的函数construct()
从未被调用。你应该把它命名为__construct()
。