2

是否可以获得已实现接口的方法?

例如,只返回接口中的函数 bar()。

interface iFoo  
{   
  public function bar(); 
}

class Foo implements iFoo 
{   
  public function bar()
  { 
    ...
  }

  public function fooBar()
  {
    ...
  }
}


我知道我可以使用 class_implements 返回实现的接口,例如

print_r(class_implements('Foo'));

output:
Array ( [iFoo] => iFoo ) 

如何获取已实现接口的方法?

4

3 回答 3

3

您可以使用Reflection

$iFooRef = new ReflectionClass('iFoo');
$methods = $iFooRef->getMethods();
print_r( $methods);

哪个输出:

Array
(
    [0] => ReflectionMethod Object
        (
            [name] => bar
            [class] => iFoo
        )
)

如果你想在一个对象上调用iFooref 中定义的方法,你可以这样做:Foo

// 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));
}
于 2013-07-10T14:19:47.167 回答
3

根据定义,实现接口意味着您必须ALL在子类中定义方法,因此您要查找的是ALL接口中的方法。

单接口:

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

输出:

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

多个接口:

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

输出:

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

uFoo为您的示例添加了界面:

interface uFoo {
    public function ubar();
}

interface iFoo  
{   
  public function bar(); 
}

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

  public function fooBar()
  {
  }
  public function ubar(){}
}
于 2013-07-10T14:18:37.983 回答
1

你不需要有一个具体的接口实现来知道一个已知接口实现应该有的方法。同样ReflectionClass可以做到这一点:

interface ExampleInterface
{
    public function foo();
    public function bar();
}

$reflection = new ReflectionClass(ExampleInterface::class);

var_dump($reflection->isInterface());

$methods = $reflection->getMethods();

var_dump($methods[0]);

输出:

bool(true)
object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(3) "foo"
  ["class"]=>
  string(16) "ExampleInterface"
}

此外,不出所料,get_class_methods对于接口也可以正常工作:

get_class_methods(ExampleInterface::class);
// returns ['foo', 'bar']
于 2019-09-12T03:24:30.543 回答