是否可以获得已实现接口的方法?
例如,只返回接口中的函数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 )
如何获得已实现接口的方法?
您可以使用Reflection
:
$iFooRef = new ReflectionClass('iFoo');
$methods = $iFooRef->getMethods();
print_r( $methods);
哪个输出:
Array
(
[0] => ReflectionMethod Object
(
[name] => bar
[class] => iFoo
)
)
如果要在Foo
对象上调用iFoo
ref中定义的方法,可以执行以下操作:
// 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));
}
根据定义,实现接口意味着您必须在子类中定义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(){}
}
您不需要有一个接口的具体实现就可以知道一个已知接口实现应该具有的方法。相同的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']