PHP 检查属性是否存在于对象或类中 [英] PHP check whether property exists in object or class
本文介绍了PHP 检查属性是否存在于对象或类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道 PHP 没有纯对象变量,但我想检查一个属性是否在给定的对象或类中.
$ob = (object) array('a' => 1, 'b' => 12);
或
$ob = 新标准类;$ob->a = 1;$ob->b = 2;
在JS,我可以写这个来检查变量a
是否存在于一个对象中:
if ('a' in ob)
在PHP 中,可以做这样的事情吗?
解决方案
property_exists(mixed $类,字符串 $property )
if (property_exists($ob, 'a'))
isset(混合 $var [, 混合 $... ] )
if (isset($ob->a))
<块引用>
如果属性为空,isset() 将返回 false
示例 1:
$ob->a = nullvar_dump(isset($ob->a));//错误的
示例 2:
class Foo{公共 $bar = null;}$foo = new Foo();var_dump(property_exists($foo, 'bar'));//真的var_dump(isset($foo->bar));//错误的
I understand PHP does not have a pure object variable, but I want to check whether a property is in the given object or class.
$ob = (object) array('a' => 1, 'b' => 12);
or
$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;
In JS, I can write this to check if variable a
exists in an object:
if ('a' in ob)
In PHP, can anything like this be done?
解决方案
property_exists( mixed $class , string $property )
if (property_exists($ob, 'a'))
isset( mixed $var [, mixed $... ] )
if (isset($ob->a))
isset() will return false if property is null
Example 1:
$ob->a = null
var_dump(isset($ob->a)); // false
Example 2:
class Foo
{
public $bar = null;
}
$foo = new Foo();
var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false
这篇关于PHP 检查属性是否存在于对象或类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文