首页 > 解决方案 > 如何找到方法的属性预期的类类型?

问题描述

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

<?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';
}
...
?>

标签: phpreflectiontype-hinting

解决方案


好的,向 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();

推荐阅读