如果类构造函数设置该类的属性,是否仍建议检查是否在其他方法中设置了该属性?代码:
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; }
}
}
我只是习惯检查是否设置了变量,只是想知道是否存在任何问题。谢谢!
答案 0 :(得分:1)
这取决于你想要达到的目标。
如果属性为isset($this->property)
,则在您的特定情况下, true
将为null
。如果这就是你想要的 - 那么最好是检查null
是否明确
if ($this->property === null)
如果这不是你想要的,你只想确保属性存在,那么它是多余的,因为:
unset
属性,因为它是公开的(无论如何这都是个坏主意) - 然后将其设为private
或protected
并且不要公开直接访问它,但提供一个getter而不是