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



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

我有一个名为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]将是类的方法,那么我只是ReflectionMethod即可获得该方法的参数,然后,我试图获得参数类型,这是我所困扰的,因为它只是不断返回一个空的对象:

反射namedtype对象{(

那么,我的问题是,为什么它返回一个空对象,我该如何获得参数的类型?

您必须进行echo而不是print_r

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

因为ReflectionType使用__toString()显示它。

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

最新更新