How do I get the type of constructor parameter via reflection?

后端 未结 3 1075
自闭症患者
自闭症患者 2020-12-10 01:31

I\'m using type hinting on my constructor parameter list like so:

public function __construct(FooRepository $repository)

Is there a way to

3条回答
  •  遥遥无期
    2020-12-10 01:57

    Check out PHP 5.4

    They are planning to get out PHP 5.4 this year, which will have the reflection method (current in the dev builds) of parameter->getHint()

    However, until 5.4 goes GA, I am using ReflectionClass::getDocComment()

    For example, you can specify it in @param.

    // Adapted from meager's example
    class Bar {}
    
    class Foo {
        /**
        * @param MyType $value
        * @param array $value2
        */
        function __construct(Bar $value, array $value2) {
        }
    }
    
    // Regex
    function getHint( $docComment, $varName ) {
        $matches = array();
        $count = preg_match_all('/@param[\t\s]*(?P[^\t\s]*)[\t\s]*\$(?P[^\t\s]*)/sim', $docComment, $matches);
        if( $count>0 ) {
            foreach( $matches['name'] as $n=>$name ) {
                if( $name == $varName ) {
                    return $matches['type'][$n];
                }
            }
        }
        return null;
    }
    
    $reflection = new ReflectionClass('Foo');
    $constructor= $reflection->getConstructor();
    $docComment = $constructor->getDocComment();
    $params = $constructor->getParameters();
    foreach ($params AS $param) {
        $name = $param->getName();
        echo $name ." is ";
        //echo $param->getHint()."\n"; // in PHP 5.4
        echo getHint($docComment, $name)."\n"; // work around
    }
    

    Output:

    value is MyType
    value2 is array
    

提交回复
热议问题