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

后端 未结 3 1071
自闭症患者
自闭症患者 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:38

    Are you trying to get the hinted type, or the actual type? I can't see why you could want to get the hinted type, as you know it is 'FooRepository' or PHP would have raised an error.

    You can get the actual type via get_class and you can also find out if a object inherits from a given class with ReflectionClass::isSubclassOf.

    0 讨论(0)
  • 2020-12-10 01:47

    Try this out.

    class Foo {
        public function __construct(Bar $test) {
        }
    }
    
    class Bar {
        public function __construct() {
        }
    }
    
    $reflection = new ReflectionClass('Foo');
    $params = $reflection->getConstructor()->getParameters();
    foreach ($params AS $param) {
        echo $param->getClass()->name . '<br>';
    }
    
    0 讨论(0)
  • 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<type>[^\t\s]*)[\t\s]*\$(?P<name>[^\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
    
    0 讨论(0)
提交回复
热议问题