PHP检查对象或类中是否存在属性 [英] PHP check whether property exists in object or class

查看:2132
本文介绍了PHP检查对象或类中是否存在属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解PHP没有纯对象变量,但是我想检查属性是否在给定的对象或类中.

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); 

$ob = new stdClass;
$ob->a = 1;
$ob->b = 2;

JS 中,我可以编写此代码来检查对象中是否存在变量a:

In JS, I can write this to check if variable a exists in an object:

if ('a' in ob)

PHP 中,可以完成这样的事情吗?

In PHP, can anything like this be done?

非常感谢您的建议.

推荐答案

property_exists(混合$ class,字符串$ property)

if (property_exists($ob, 'a')) 

isset(混合$ var [,混合$ ...])

if (isset($ob->a))

如果属性为null,

isset()将返回false

isset() will return false if property is null

示例1:

$ob->a = null
var_dump(isset($ob->a)); // false

示例2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

这篇关于PHP检查对象或类中是否存在属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆