php 测试属性是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3432779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing if property exists
提问by Jiew Meng
I read on php docsthat isset()is faster than property_exists()and we should use a combination of both like
我阅读了比php 文档isset()更快的php 文档,property_exists()我们应该使用两者的组合,例如
if (isset($this->fld) || property_exists($this, 'fld')) {
But why can't I just use isset then?
但是为什么我不能只使用 isset 呢?
if (isset($this->fld)) {
回答by prodigitalson
Because property_existswill tell you if its even a defined property of the class/object where as isset doesnt make that distinction. for example:
因为它property_exists会告诉您它是否甚至是类/对象的已定义属性,而 isset 并没有做出这种区分。例如:
class A {
protected $hello;
}
class B {
}
using property_exists($this, 'hello')in class Awill return true, while using it in class Bwill return false. issetwill return falsein bothinstances.
使用property_exists($this, 'hello')在A级将返回true,而在使用它的B类将返回false。在这两种情况下isset都会返回。false
回答by James Black
It depends on how your program is done, but if you read the comments in the manual it will help with explaining idiosyncrasies of a function.
这取决于您的程序是如何完成的,但是如果您阅读手册中的注释,它将有助于解释函数的特性。
http://php.net/manual/en/function.property-exists.php
http://php.net/manual/en/function.property-exists.php
The important part is here:
重要的部分在这里:
The documentation leaves out the important case of new properties you add to objects at run time. In fact, property_exists will return true if you ask it about such properties.
该文档忽略了在运行时添加到对象的新属性的重要情况。事实上,如果你询问这些属性,property_exists 将返回 true。

