在构造函数设置之前没有实例化的类属性 - 不好吗?

时间:2016-04-08 13:02:23

标签: php oop

偶然地,我注意到以下内容适用于PHP:

class
{
    public function __construct()
    {
        // Notice that this was not declared before use
        $this->not_declared = "Hello";
    }

    public function display()
    {
        echo $this->not_declared; // Outputs "Hello"
    }
}

这是不好的做法吗?我总是认为必须在使用前声明属性,如下所示:

class
{
    private $not_declared = "";

    public function __construct()
    {
        // In this case, it was declared above
        $this->not_declared = "Hello";
    }

    public function display()
    {
        echo $this->not_declared; // Outputs "Hello"
    }
}

0 个答案:

没有答案
相关问题