首页 文章资讯内容详情

使用PHP检查对象或类中是否存在属性

2026-06-04 1 花语

property_exists()或isset()函数可用于检查属性是否存在于类或对象中。

语法

以下是property_exists()函数的语法-

property_exists( mixed $class , string $property )

if (property_exists($object, a_property))

以下是isset()函数的语法-

isset( mixed $var [, mixed $... ] )

if (isset($object->a_property))

如果a_property为null,则isset()将返回false。

示例

让我们看一个例子-

<?php class Demo { public $one; private $two; static protected $VAL; static function VAL() { var_dump(property_exists(myClass, two)); } } var_dump(property_exists(Demo, one)); var_dump(property_exists(new Demo, one)); ?>

输出结果

bool(true) bool(true)