使用 PHP 检查对象或类中是否存在属性
phpserver side programmingprogramming更新于 2025/9/8 22:30:00
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’ 为空,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)

