首页 > 解决方案 > 在 PHP 8 中,如何通过反射检查传递对象是否有效?

问题描述

假设我有

class X {
}
class Y {
}
function foo(X|Y $param) {
}
class Z extends Y {
}
class U {
}

现在,如何验证将 Z 的实例传递给foo有效但 U 的实例无效?手动,它看起来像......

$r = new \ReflectionFunction('foo');
$found = FALSE;
foreach ($r->getParameters()[0]->getType()->getTypes() as $type) {
  $name = $type->getName();
  if ($name && is_subclass_of('\Z', $name)) {
    $found = TRUE;
  }
}

至少可以说这很难看,我什至不确定是否$name有必要进行非空检查。

PHP 8 中是否有一些“类型匹配”功能?

标签: php

解决方案


这应该工作

$r = new \ReflectionFunction('foo');
$found = FALSE;
foreach ($r->getParameters() as $parameter) {
    if ($parameter->getClass()->isSubclassOf('Z')) {
        $found = TRUE;
    }
}

https://www.php.net/manual/en/language.operators.type.php#102988


推荐阅读