List all methods of a given class, excluding parent class's methods in PHP

人盡茶涼 提交于 2020-01-31 08:20:08

问题


I'm building a unit testing framework for PHP and I was curious if there is a way to get a list of an objects methods which excludes the parent class's methods. So given this:

class Foo
{

    public function doSomethingFooey()
    {
        echo 'HELLO THERE!';
    }
}

class Bar extends Foo
{
    public function goToTheBar()
    {
        // DRINK!
    }
}

I want a function which will, given the parameter new Bar() return:

array( 'goToTheBar' );

WITHOUT needing to instantiate an instance of Foo. (This means get_class_methods will not work).


回答1:


Use ReflectionClass, for example:

$f = new ReflectionClass('Bar');
$methods = array();
foreach ($f->getMethods() as $m) {
    if ($m->class == 'Bar') {
        $methods[] = $m->name;
    }
}
print_r($methods);



回答2:


You can use get_class_methods() without instantiating the class:

$class_name - The class name or an object instance.

So the following would work:

$bar_methods = array_diff(get_class_methods('Bar'), get_class_methods('Foo'));

Assuming there aren't repeated methods in the parent class. Still, Lukman's answer does a better job. =)




回答3:


$class_methods = get_class_methods('Bar');

From the PHP Documenation

This will not instantiate the class, and will allow you to get an array of all of the classes methods.

I'm not completely certain that this won't return parent class methods, but get_class_methods will work for uninstantiated classes. If it does, you can use Alix's answer to remove the parent's method from the array. Or Lukman's to use the reverse engineering aspect of PHP internal code base to get the methods.


BTW, if you type in new Bar(), it is going to create a new instance of Foo, as Bar extends Foo. The only way you can not instantiate Foo is by referring to it statically. Therefore, your request:

I want a function which will, given the parameter new Bar() return:

Has no possible solution. If you give new Bar() as an argument, it will instantiate the class.




回答4:


For anyone else wondering how to check if specific method belongs to specified class or its parent class, you can do this by getting its class name and then comparing it with actual class name like following.

$reflection = new \ReflectionMethod($classInstance, 'method_name_here');
if($reflection->class == MyClass::class)
echo "Method belongs to MyClass";
else
echo "Method belongs to Parent classes of MyClass";


来源:https://stackoverflow.com/questions/2010889/list-all-methods-of-a-given-class-excluding-parent-classs-methods-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!