测试属性是否存在

时间:2010-08-08 01:53:09

标签: php

我在php docs上看到isset()property_exists()快,我们应该使用两者的组合

if (isset($this->fld) || property_exists($this, 'fld')) { 

但为什么我不能只使用isset呢?

if (isset($this->fld)) {

2 个答案:

答案 0 :(得分:79)

因为property_exists会告诉你它是否甚至是一个定义的类/对象属性,而asset也没有这个区别。例如:

class A {
  protected $hello;
}

class B {

}

A类中使用property_exists($this, 'hello')将返回true,而在 B类中使用它将返回falseisset将在两个实例中返回false

答案 1 :(得分:5)

这取决于你的程序是如何完成的,但是如果你阅读了手册中的注释,它将有助于解释函数的特性。

http://php.net/manual/en/function.property-exists.php

重要的部分在这里:

  

文档遗漏了   新属性的重要案例你   在运行时添加到对象。事实上,   如果,property_exists将返回true   你问这个属性。

相关问题