0

由于某种原因,我无法让它工作:

<?php 
class Number{
    public $number;
    public $number_added;


    public function __construct(){
        $this->number_added = $this->add_two();
    }

    public function add_two(){
        return $this->number + 2;
    }
}   
?>

$this->number从数据库设置,$this->number_two应该是 DB 值 + 2。但是,当我 echo 时$this->number_added,它返回两个。该$number值已正确初始化。这是我的问题的一个简化示例,只是为了看看我想要做的事情是否可行?PHP OOP 初学者。

4

1 回答 1

3

在使用之前(通过构造函数),您没有在$number任何地方设置属性add_two(),因此 PHP0在添加期间对其进行评估。

例如,您应该在对象构造期间传入初始状态

public function __construct($number) {
    $this->number = $number;

    $this->number_added = $this->add_two();
}

更新

请允许我说明问题。这是您当前的代码以及我想象您如何使用它

$number = 2;

$obj = new Number();
// right here, $obj->number is null (0 in a numeric sense)
// as your constructor calls add_two(), $obj->number_added is 2 (0 + 2)

$obj->number = $number;
// now $obj->number is 2 whilst $obj->number_added remains 2

使用我更新的构造函数,这就是发生的事情

$number = 2;

$obj = new Number($number);
// $obj->number is set to $number (2) and a call to add_two() is made
// therefore $obj->number_added is 4
于 2013-02-05T00:12:34.577 回答