3

I'm trying to get type $bar variable.

<?php
class Foo
{
    public function test(stdClass $bar, array $foo)
    {

    }
}

$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
    foreach ($method->getParameters() as $num => $parameter) {
        var_dump($parameter->getType());
    }
}

I expect stdClass but I get

Call to undefined method ReflectionParameter::getType()

What can be wrong? Or there is some another way?..

$ php -v
PHP 5.4.41 (cli) (built: May 14 2015 02:34:29)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

UPD1 It should work for the array type as well.

Kirby
  • 2,847
  • 2
  • 32
  • 42

2 Answers2

3

If you're only type hinting classes, you can use ->getClass() which is supported in PHP 5 and 7.

<?php

class MyClass {

}

class Foo
{
    public function test(stdClass $bar)
    {

    }

    public function another_test(array $arr) {

    }

    public function final_test(MyClass $var) {

    }
}

$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
    foreach ($method->getParameters() as $num => $parameter) {
        var_dump($parameter->getClass());
    }
}

The reason I say classes, is because on an array, it will return NULL.

Output:

object(ReflectionClass)#6 (1) {
  ["name"]=>
  string(8) "stdClass"
}
NULL
object(ReflectionClass)#6 (1) {
  ["name"]=>
  string(7) "MyClass"
}
Dave Chen
  • 10,887
  • 8
  • 39
  • 67
  • Yeah, it works. Thanks! So, `$parameter->getClass() ? $parameter->getClass()->name : null;`. I don't know why didn't notice that.) Seem it's too late, 9pm. :) – Kirby Mar 28 '16 at 18:12
  • I mentioned it as one of the caveats, if this is important either (1) upgrade to php 7, or (2) use `->export` and mangle raw source code text with regex. – Dave Chen Mar 28 '16 at 18:22
2

It looks like similar question already added in PHP Reflection - Get Method Parameter Type As String

I wrote my solution it works for all cases:

/**
 * @param ReflectionParameter $parameter
 * @return string|null
 */
function getParameterType(ReflectionParameter $parameter)
{
    $export = ReflectionParameter::export(
        array(
            $parameter->getDeclaringClass()->name,
            $parameter->getDeclaringFunction()->name
        ),
        $parameter->name,
        true
    );
    return preg_match('/[>] ([A-z]+) /', $export, $matches)
        ? $matches[1] : null;
}
Community
  • 1
  • 1
Kirby
  • 2,847
  • 2
  • 32
  • 42