我在 php docs 上阅读isset()
比 property_exists()
快,我们应该将两者结合使用
if (isset($this->fld) || property_exists($this, 'fld')) {
但是为什么我不能只使用 isset 呢?
if (isset($this->fld)) {
最佳答案
因为 property_exists
会告诉您它是否甚至是类/对象的已定义属性,而 asisset 没有做出这种区分。例如:
class A {
protected $hello;
}
class B {
}
在 class A 中使用 property_exists($this, 'hello')
将返回 true
,而在 class B 中使用它 将返回 false
。 isset
将在 both 实例中返回 false
。
关于php - 测试属性是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3432779/