对php对象如何处理数组感到困惑

时间:2011-12-06 23:20:33

标签: php

当我期望“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();

为什么我的期望被打破了?

3 个答案:

答案 0 :(得分:9)

您的构造函数未触发它需要调用:

public function __construct(){
 // constructor
}

否则数组无法初始化。

答案 1 :(得分:4)

您的问题基本上归结为something()开头的行,问:

  

$ this->此时数组是空的,为什么?

这是因为PHP构造函数需要命名为__construct,而您的构造函数只需命名为construct

答案 2 :(得分:2)

永远不会调用您的函数construct()。您应该将其命名为__construct()

相关问题