php get interface methods

2019-05-29 14:33发布

问题:

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?

回答1:

By definition, implementing an interface means that you must define ALL methods in the child class, so what you are looking for is ALL of the methods from the interface(s).

Single interface:

$interface = class_implements('Foo');
$methods_implemented = get_class_methods(array_shift($interface));
var_dump($methods_implemented);

Outputs:

array (size=1)
  0 => string 'bar' (length=3)

Multiple Interfaces:

$interfaces = class_implements('Foo');

$methods_implemented = array();
foreach($interfaces as $interface) {
    $methods_implemented = array_merge($methods_implemented, get_class_methods($interface));
}
var_dump($methods_implemented);

Outputs:

array (size=2)
  0 => string 'bar' (length=3)
  1 => string 'ubar' (length=4)

Added interface uFoo to your example:

interface uFoo {
    public function ubar();
}

interface iFoo  
{   
  public function bar(); 
}

class Foo implements iFoo, uFoo
{   
  public function bar()
  { 
  }

  public function fooBar()
  {
  }
  public function ubar(){}
}


回答2:

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