php - 如何找到方法的属性预期的类类型?
问题描述
我需要查看方法属性的预期类类型(类型提示)。
<?php
class Foo {}
class Bar {
public function do(Foo $foo_instance) {}
}
$bar = new Bar();
$some_instance = new ??();
$bar->do($some_instance);
?>
我认为这是反射 API'Foo'
中可用的东西,但我还没有找到任何作为我的类型提示吐出的东西Bar::do
。有任何想法吗?
语境
我想做类似的事情:
<?php
...
if ( myMethodExpects($class, $method, 'Foo') ) {
$some_instance = new Foo();
} elseif ( myMethodExpects($class, $method, 'Baz') {
$some_instance = new Baz();
} elseif ( myMethodHasNoTypeHint($class, $method) ) {
$some_instance = 'just a string';
}
...
?>
解决方案
好的,向 Google 提出了正确的问题。
我在寻找ReflectionParameter::getClass。像这样使用:
<?php
class Foo {
public function do(Bar $bar, Baz $baz, $foo='') {}
}
$method = new ReflectionMethod('Foo', 'do');
$method_params = $method->getParameters();
foreach ( $method_params as $param ) {
var_dump($param->getClass());
}
?>
/* RETURNS
-> object(ReflectionClass)[6]
public 'name' => string 'Bar' (length=3)
-> object(ReflectionClass)[6]
public 'name' => string 'Baz' (length=4)
-> null
*/
这也可以用于ReflectionFunction
:
$function_params = (new ReflectionFunction('func_name')->getParameters();
推荐阅读
- javascript - 带进度条的 24 小时倒数计时器
- c++ - 如何在 C++ 中将带有空格的字符数组写入二进制文件?以及如何阅读它们?
- c# - 使用 LINQ 遍历列表加一个值
- flutter - Dart/fultter:如何在模拟器的本地主机上显示来自 API 的图像
- reactjs - TypeError无法读取nativebase未定义的属性“样式”
- angular - 使用 http.get() 检索 xlsx 文件,然后将所述文件加载到 Angular 中的 ExcelJs
- ios - Ios 强制门户 Google oauth 不允许代理 - Angular 应用程序
- c# - 如何使用 HtmlAgilityPack 获得追随兄弟姐妹?
- javascript - 如何从 React/Jest 中的自定义钩子模拟返回数据?
- node.js - 禁止节点应用程序访问全局 npm 模块,或者至少发出警告?