Kirby
Kirby

Reputation: 3117

How to get parameter type in reflected class method (PHP 5.x)?

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.

Upvotes: 3

Views: 2489

Answers (2)

Dave Chen
Dave Chen

Reputation: 10975

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"
}

Upvotes: 3

Kirby
Kirby

Reputation: 3117

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;
}

Upvotes: 2

Related Questions