cwa*_*ole 10 php oop methods class
我正在为PHP构建一个单元测试框架,我很好奇是否有办法获取排除父类方法的对象方法列表.所以这个:
class Foo
{
public function doSomethingFooey()
{
echo 'HELLO THERE!';
}
}
class Bar extends Foo
{
public function goToTheBar()
{
// DRINK!
}
}
Run Code Online (Sandbox Code Playgroud)
我想要一个函数,给定参数new Bar()返回:
array( 'goToTheBar' );
Run Code Online (Sandbox Code Playgroud)
无需实例化Foo的实例.(这意味着get_class_methods不起作用).
Luk*_*man 27
使用ReflectionClass,例如:
$f = new ReflectionClass('Bar');
$methods = array();
foreach ($f->getMethods() as $m) {
if ($m->class == 'Bar') {
$methods[] = $m->name;
}
}
print_r($methods);
Run Code Online (Sandbox Code Playgroud)
您可以在get_class_methods()不实例化类的情况下使用:
$ class_name - 类名或对象实例.
所以以下方法可行:
$bar_methods = array_diff(get_class_methods('Bar'), get_class_methods('Foo'));
Run Code Online (Sandbox Code Playgroud)
假设父类中没有重复的方法.尽管如此,Lukman的回答还是做得更好.=)