测试属性是否存在

Jie*_*eng 58 php

我读了PHP的文档isset()比快property_exists(),我们应该使用这样两者的结合

if (isset($this->fld) || property_exists($this, 'fld')) { 
Run Code Online (Sandbox Code Playgroud)

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

if (isset($this->fld)) {
Run Code Online (Sandbox Code Playgroud)

pro*_*son 80

因为它property_exists会告诉你它是否甚至是一个定义的类/对象的属性,因为isset没有做出这种区分.例如:

class A {
  protected $hello;
}

class B {

}
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*ack 5

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

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

重要的是这里:

该文档省略了在运行时添加到对象的新属性的重要案例.事实上,如果你问这些属性,property_exists将返回true.

  • 如果属性不为空,我也更喜欢isset进行测试 (3认同)