1

私有变量

class Input {
    private
        $form;

    public function __construct (Form $form) {
        $this->form = $form;
    }

    public function getForm () {
        return $this->form;
    }
}

带有静态变量的方法

class Input {
    public function __construct (Form $form) {
        $this->getForm($form);
    }

    public function getForm (Form $set_form = null) {
        static $form;

        if (!$form && $set_form !== null) {
            $form = $set_form;
        } else if ($form && $set_form) {
            throw new \ErrorException('Form has been already set.');
        }

        return $form;
    }
}

我更喜欢后者,因为转储对象$form时不包括属性。Input由于它们的循环关系(示例中未显示),它使输出不可读。

使用后一种方法 VS 后一种方法有什么缺点?

4

1 回答 1

3

方法中的static变量在类的所有实例中都是常量,private属性根本无法从类外部访问,但对于它的每个实例都是唯一的。它们根本不一样。如果您需要每个类实例唯一的属性,则无法替代属性。它也比您static对同一事物的解决方法更具可读性和惯用性。

var_dump如果这是您使用static变量的唯一原因,请学会更好地阅读。

于 2013-10-03T10:18:41.610 回答