Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get interface methods

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?

like image 229
jrl05k Avatar asked May 04 '26 11:05

jrl05k


1 Answers

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));
}
like image 149
nickb Avatar answered May 05 '26 23:05

nickb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!