ReflectionMethod的get类型重新调整了一个空对象

时间:2018-02-08 19:34:30

标签: php

所以,我正在尝试获取方法的类型,以实例化类,例如:

我有一个名为mycontroller的类和一个名为page的简单方法,它有一个类型提示,例如:

class MyController
{
    public function page(AnotherClass $class)
    {
        $class->intro;
    }
}

我还有另一个课程,简称为anotherclass(非常原创,我知道)

class AnotherClass
{
    public $intro = "Hello";
}

好的,这是基础知识,现在我正在尝试获取MYControllers方法参数页面的类型:anotherclass

您可以在下面看到我的代码的逻辑:

Class Route
{
    /**
     * Method paramaters
     *
     * @var array
     */
    protected $params;

    /**
     * The class and method
     *
     * @var array
     */
    protected $action;

    /**
     * Get the paramaters of a callable function
     *
     * @return void
     */
    public function getParams()
    {
       $this->params = (new ReflectionMethod($this->action[0], $this->action[1]))->getParameters();
    }

    /**
     * Seperate the class and method
     *
     * @param [type] $action
     * @return void
     */
    public function getClassAndMethod($action = null)
    {
        $this->action = explode("@", $action);

    }

    /**
     * A get request
     *
     * @param string $route
     * @return self
     */
    public function get($route = null)
    {   
        if(is_null($route)) {
            throw new Exception("the [$route] must be defined");
        }

        return $this;
    }

    public function uses($action = null)
    {
        if(is_null($action)){
            throw new Exception("the [$action] must be set");
        }  

        if(is_callable($action)){
            return call_user_func($action);
        }

        // Get the action
        $this->getClassAndMethod($action);

        // Get the params of the method
        $this->getParams();

        foreach ($this->params as $param) {

            print_R($param->getType());
        }

        // var_dump($action[0]);
    }
}

这就像这样被调用:

echo (new Route)->get('hello')->uses('MyController@page');

那么,以上是什么,它是通过@符号拆分使用方法参数,[0]将是类,[1]将是类&#39;方法,然后我只是ReflectionMethod来获取所述方法的参数,然后我试图获取参数类型,这是我坚持的,因为它只是不断返回一个空对象:< / p>

  

ReflectionNamedType Object {)

所以,我的问题是,为什么它返回一个空对象,我怎样才能得到参数的类型?

1 个答案:

答案 0 :(得分:2)

您必须echo而不是print_r

foreach ($this->params as $param) {
    echo $param->getType() ; //AnotherClass
}

由于ReflectionType使用__toString()来显示它。

或者

foreach ($this->params as $param) {
    print_r($param->getClass()) ; //AnotherClass
}