检查属性是否在课堂上设置

时间:2014-03-26 23:11:34

标签: php

如果类构造函数设置该类的属性,是否仍建议检查是否在其他方法中设置了该属性?代码:

class A {

    public $property;

    public function __construct($value) {
        $this->property = $value;
    }

    public function doSomething() {

        if(isset($this->property)) {
            //actual code here
            //...but is this isset-check necessary?
        }
        else { return false; }
    }
} 

我只是习惯检查是否设置了变量,只是想知道是否存在任何问题。谢谢!

1 个答案:

答案 0 :(得分:1)

这取决于你想要达到的目标。

如果属性为isset($this->property),则在您的特定情况下,

true将为null。如果这就是你想要的 - 那么最好是检查null是否明确

if ($this->property === null)

如果这不是你想要的,你只想确保属性存在,那么它是多余的,因为:

  1. 宣布财产后 - 它将会在那里
  2. 如果您担心某些代码unset属性,因为它是公开的(无论如何这都是个坏主意) - 然后将其设为privateprotected并且不要公开直接访问它,但提供一个getter而不是
相关问题