php - 在 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 中是否有一些“类型匹配”功能?
解决方案
这应该工作
$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
推荐阅读
- android - MediaManager 从 android 中的 url 缓冲 mp3 文件的时间太长
- excel - 防止 Excel 文件被共享到另一台计算机
- mongodb - MongoDB Shell SyntaxError:意外令牌:字符串文字
- arrays - 有没有更有效的方法在数组中分配非零元素?
- c# - C# winfrom 当我使用 showdialog 打开一个新的模式窗口并关闭它时,UI 控件资源会发生什么?
- .htaccess - htaccess 和 codeigniter 错误重定向 URL 中奇怪的问号
- google-apps-script - 如何在将应用程序脚本呈现给用户浏览器之前使用应用程序脚本授权 Google 表单
- excel - 在 Excel 上绘制图形
- amazon-web-services - aws 托管仅通过 vpn 工作
- excel - Flask 应用程序下载存档而不是 Excel 文件