This question already has an answer here:
I need to see what class type is being expected (type-hinted) for a method property.
<?php
class Foo {}
class Bar {
public function do(Foo $foo_instance) {}
}
$bar = new Bar();
$some_instance = new ??();
$bar->do($some_instance);
?>
I think this is something available in the Reflection API, but I have yet to find anything that spits out 'Foo'
as my type-hint for Bar::do
. Any ideas?
I want to do something like:
<?php
...
if ( myMethodExpects($class, $method, 'Foo') ) {
$some_instance = new Foo();
} elseif ( myMethodExpects($class, $method, 'Baz') {
$some_instance = new Baz();
} elseif ( myMethodHasNoTypeHint($class, $method) ) {
$some_instance = 'just a string';
}
...
?>
</div>
Okay, asked Google the right questions.
I was looking for ReflectionParameter::getClass. Used like so:
<?php
class Foo {
public function do(Bar $bar, Baz $baz, $foo='') {}
}
$method = new ReflectionMethod('Foo', 'do');
$method_params = $method->getParameters();
foreach ( $method_params as $param ) {
var_dump($param->getClass());
}
?>
/* RETURNS
-> object(ReflectionClass)[6]
public 'name' => string 'Bar' (length=3)
-> object(ReflectionClass)[6]
public 'name' => string 'Baz' (length=4)
-> null
*/
This can also be used on ReflectionFunction
:
$function_params = (new ReflectionFunction('func_name')->getParameters();