php - 如何在反射类方法(PHP 5.x)中获取参数类型?

标签 php reflection parameters php-5.4

我正在尝试获取类型 $bar 变量。

<?php
class Foo
{
    public function test(stdClass $bar, array $foo)
    {

    }
}

$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
    foreach ($method->getParameters() as $num => $parameter) {
        var_dump($parameter->getType());
    }
}

我期望 stdClass 但我得到了

Call to undefined method ReflectionParameter::getType()

有什么问题吗?还是有别的办法?..

$ php -v
PHP 5.4.41 (cli) (built: May 14 2015 02:34:29)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

UPD1 它也应该适用于数组类型。

最佳答案

如果你只是类型提示类,你可以使用 ->getClass() PHP 5 和 7 支持。

<?php

class MyClass {

}

class Foo
{
    public function test(stdClass $bar)
    {

    }

    public function another_test(array $arr) {

    }

    public function final_test(MyClass $var) {

    }
}

$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
    foreach ($method->getParameters() as $num => $parameter) {
        var_dump($parameter->getClass());
    }
}

我之所以说类,是因为在数组上,它会返回 NULL。

Output :

object(ReflectionClass)#6 (1) {
  ["name"]=>
  string(8) "stdClass"
}
NULL
object(ReflectionClass)#6 (1) {
  ["name"]=>
  string(7) "MyClass"
}

关于php - 如何在反射类方法(PHP 5.x)中获取参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36267390/

相关文章:

php - Kohana 3 中的 i18n 和错误消息

javascript - Java 或任何其他语言中类似于 JavaScript 对象的数据结构的正确/首选名称是什么?

c# - 如何拦截 C# 中的方法调用?

javascript - 多态参数javascript

python - 将 "python2.7 -c"输出作为 C 文件的参数传递

parameters - 是否可以以某种方式创建类似 typeof 的函数

php - mysql 查询需要一些循环或数组

reflection - 使用嵌入在结构中的接口(interface)进行反射 - 如何检测 "real"函数?

Scala 2.10反射: constructor of case class inside a class

php - select关键字无法插入到mysql表中