Is it possible to get the methods of an implemented interface?
For example, to return only function bar() that is in interface.
interface iFoo
{
public function bar();
}
class Foo implements iFoo
{
public function bar()
{
...
}
public function fooBar()
{
...
}
}
I know I can use class_implements to return the implemented interfaces, for example
print_r(class_implements('Foo'));
output:
Array ( [iFoo] => iFoo )
How do I get the methods of the implemented interfaces?
You can use Reflection:
$iFooRef = new ReflectionClass('iFoo');
$methods = $iFooRef->getMethods();
print_r( $methods);
Which outputs:
Array
(
[0] => ReflectionMethod Object
(
[name] => bar
[class] => iFoo
)
)
If you want to call the methods defined in iFoo ref on a Foo object, you can do:
// Optional: Make sure Foo implements iFooRef
$fooRef = new ReflectionClass('Foo');
if( !$fooRef->implementsInterface('iFoo')) {
throw new Exception("Foo must implement iFoo");
}
// Now invoke iFoo methods on Foo object
$foo = new Foo;
foreach( $iFooRef->getMethods() as $method) {
call_user_func( array( $foo, $method->name));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With