This function has a flaw in PHP versions < 5.3.* (my tested version was 5.3.2), in which class inheritance is not handled properly. The following test case renders true in 5.3.2, but false on 5.2.9:
<?php
class A {
}
class B extends A {
public function foo(A $a) {
}
}
$b = new B();
$class = new ReflectionClass('B');
$method = $class->getMethod('foo');
$parameters = $method->getParameters();
$param = $parameters[0];
$class = $param->getClass();
var_dump($class->isInstance($b));
?>
If you're running a PHP version lower than 5.3, my suggestion is to use the following fix:
<?php
[...]
$param = $parameters[0];
$class = $param->getClass();
$classname = $class->getName();
var_dump($b instanceof $classname);
?>
ReflectionClass::isInstance
(PHP 5)
ReflectionClass::isInstance — 检查类的实例
说明
public bool ReflectionClass::isInstance
( object
$object
)检查对象是否为一个类的实例。
参数
-
object -
待比较的对象。
返回值
成功时返回 TRUE, 或者在失败时返回 FALSE。
范例
Example #1 ReflectionClass::isInstance() 相关例子
<?php
// Example usage
$class = new ReflectionClass('Foo');
if ($class->isInstance($arg)) {
echo "Yes";
}
// Equivalent to
if ($arg instanceof Foo) {
echo "Yes";
}
// Equivalent to
if (is_a($arg, 'Foo')) {
echo "Yes";
}
?>
以上例程的输出类似于:
Yes Yes Yes
参见
- ReflectionClass::isInterface() - 检查类是否是一个接口(interface)
- 类型运算符(instanceof)
- 对象接口
- is_a() - 如果对象属于该类或该类是此对象的父类则返回 TRUE
Peter Kruithof ¶
2 years ago
