示例
类的特征检测可以部分通过property_existsandmethod_exists函数完成。class MyClass {
public $public_field;
protected $protected_field;
private $private_field;
static $static_field;
const CONSTANT = 0;
public function public_function() {}
protected function protected_function() {}
private function private_function() {}
static function static_function() {}
}
// 检查属性
$check = property_exists('MyClass', 'public_field'); // 真
$check = property_exists('MyClass', 'protected_field'); // 真
$check = property_exists('MyClass', 'private_field'); // 真, as of PHP 5.3.0
$check = property_exists('MyClass', 'static_field'); // 真
$check = property_exists('MyClass', 'other_field'); // 假
// 检查方法
$check = method_exists('MyClass', 'public_function'); // 真
$check = method_exists('MyClass', 'protected_function'); // 真
$check = method_exists('MyClass', 'private_function'); // 真
$check = method_exists('MyClass', 'static_function'); // 真
// 然而...
$check = property_exists('MyClass', 'CONSTANT'); // 假
$check = property_exists($object, 'CONSTANT'); // 假
使用ReflectionClass,还可以检测到常量:$r = new ReflectionClass('MyClass');
$check = $r->hasProperty('public_field'); // 真
$check = $r->hasMethod('public_function'); // 真
$check = $r->hasConstant('CONSTANT'); // 真
// 也适用于受保护的,私有的和/或静态的成员。
注意:对于property_exists和method_exists,还可以提供感兴趣的类的对象代替类名。使用反射,ReflectionObject应使用类代替ReflectionClass。