26

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

public function __construct(FooRepository $repository)

Is there a way to use the PHP Reflection API to get the hinted type? In other words, I want a reflection function that I can call to somehow get back the string "FooRepository". I've tried getting the constructor via reflection and then getting the parameters if the constructor, but I don't see anything that will give me the string of the hinted type.

1
  • 5
    Eventually, this was written into Laravel's IoC Container - bravo @taylorotwell!
    – mauris
    Commented Nov 2, 2013 at 13:43

3 Answers 3

43

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>';
}
7
  • +1 That's awesome. And I was doing it the a lengthy way before. They really should document Reflection one day.
    – netcoder
    Commented Nov 24, 2010 at 0:34
  • This only works for classes, any other hint will fail with a "Class *** does not exist" exception.
    – Alix Axel
    Commented Feb 1, 2013 at 19:58
  • 6
    @AlixAxel Actually only classes and arrays are allowed for type hinting. You should check ReflectionParameter::isArray() first
    – hek2mgl
    Commented May 22, 2013 at 13:09
  • 3
    @hek2mgl even better $param->getType()->getName() for getting the type. That doesn't require retrieving a class and allows scalar types as well. Commented May 20, 2020 at 8:57
  • simshaun: what is alternate to $param->getClass()->name as getClass() has been deprecated in php 8.
    – C.F.G
    Commented Feb 13, 2023 at 10:54
0

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
4
  • +1, but PHP 5.4.7 and still no sign of ReflectionParameter::getHint() :(.
    – Alix Axel
    Commented Feb 1, 2013 at 19:59
  • @AlixAxel, sadly I've moved away from PHP over the last several years due to complete lack of vision/focus from the language devs. :( Commented Feb 2, 2013 at 3:16
  • 1
    Oh, ok. Just out of curiosity, what did you chose to take it's place?
    – Alix Axel
    Commented Feb 2, 2013 at 11:55
  • @AlixAxel Java mostly. Fancy it more than C#. Language has a great timeline. No ideal if PHP 6 will ever happen. Commented Feb 4, 2013 at 2:16
-1

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.

3
  • I can see where this would come in handy in an MVC framework for dynamically loading the files for model classes and dynamically mapping post/get data to the objects. Commented Dec 22, 2010 at 20:54
  • @Twisted There is a difference between the type and the hinted type. Re-read my answer, you missed the point completely.
    – user229044
    Commented May 11, 2011 at 0:15
  • 1
    @meager Allow me to rephrase. I assert that there are many cases where you would want to know the hinted type. For example, you could easily create some setPropX(myType $value) methods in a ORM object class. Then, your ORM implementation can reflect to get the hint so that you know what type to cast to. Commented May 11, 2011 at 15:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.