是否可以获取已实现接口的方法?
例如,仅返回界面中的函数 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 http://php.net/reflection:
$iFooRef = new ReflectionClass('iFoo');
$methods = $iFooRef->getMethods();
print_r( $methods);
哪个输出:
Array
(
[0] => ReflectionMethod Object
(
[name] => bar
[class] => iFoo
)
)
如果你想调用定义的方法iFoo
参考一个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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)