函数名称:property_exists()
函数描述:property_exists() 函数检查对象或类是否具有指定的属性。
参数:
- $class:必需。要检查的类名或对象。
- $property:必需。要检查的属性名。
返回值:
- 若属性存在且可访问,则返回 true。
- 若属性不存在或不可访问,则返回 false。
适用版本:PHP 4, PHP 5, PHP 7
用法示例:
- 检查类是否具有指定属性:
class MyClass {
public $name = "John";
private $age = 25;
}
$object = new MyClass();
if (property_exists($object, 'name')) {
echo "The 'name' property exists.";
} else {
echo "The 'name' property does not exist.";
}
// 输出:The 'name' property exists.
- 检查对象是否具有指定属性:
class MyClass {
public $name = "John";
private $age = 25;
}
$object = new MyClass();
if (property_exists($object, 'age')) {
echo "The 'age' property exists.";
} else {
echo "The 'age' property does not exist.";
}
// 输出:The 'age' property does not exist.
- 检查类名是否具有指定静态属性:
class MyClass {
public static $name = "John";
private static $age = 25;
}
if (property_exists('MyClass', 'name')) {
echo "The 'name' static property exists.";
} else {
echo "The 'name' static property does not exist.";
}
// 输出:The 'name' static property exists.
- 检查类名是否具有指定静态私有属性:
class MyClass {
public static $name = "John";
private static $age = 25;
}
if (property_exists('MyClass', 'age')) {
echo "The 'age' static property exists.";
} else {
echo "The 'age' static property does not exist.";
}
// 输出:The 'age' static property does not exist.