如何找到方法的属性所期望的类类型?

时间:2018-11-21 15:21:31

标签: php reflection type-hinting

我需要查看方法属性期望的类类型(类型提示)。

<?php

class Foo {}

class Bar {
    public function do(Foo $foo_instance) {}
}

$bar = new Bar();
$some_instance = new ??();
$bar->do($some_instance);

?>

认为这是Reflection 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';
}
...
?>

1 个答案:

答案 0 :(得分:0)

好的,问谷歌正确的问题。

我一直在寻找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();