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 を返します。
例
例1 ReflectionClass::isInstance() の例
<?php
// 使用例
$class = new ReflectionClass('Foo');
if ($class->isInstance($arg)) {
echo "Yes";
}
// これも同じ意味です
if ($arg instanceof Foo) {
echo "Yes";
}
// これも同じ意味です
if (is_a($arg, 'Foo')) {
echo "Yes";
}
?>
上の例の出力は、 たとえば以下のようになります。
Yes Yes Yes
参考
- ReflectionClass::isInterface() - このクラスがインターフェイスであるかどうかを調べる
- 型演算子 (instanceof)
- オブジェクト インターフェイス
- is_a() - オブジェクトがこのクラスのものであるか、このクラスをその親クラスのひとつとしているかどうかを調べる
Peter Kruithof ¶
2 years ago
