Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 372
cwallenpoole Avatar asked Jan 06 '10 04:01

cwallenpoole


People also ask

How can I see all class methods in PHP?

PHP | get_class_methods() Function The get_class_methods() function is an inbuilt function in PHP which is used to get the class method names. Parameters: This function accepts a single parameter $class_name which holds the class name or an object instance.

What are methods in PHP?

Methods are used to perform actions. In Object Oriented Programming in PHP, methods are functions inside classes. Their declaration and behavior are almost similar to normal functions, except their special uses inside the class.

How to extend classes in PHP?

A class extends another by using the “extends” keyword in its declaration. If we wanted to extend WP_Query, we would start our class with “product_query extends WP_Query.” Any class can be extended unless it is declared with the final keyword.

Does PHP have inheritance?

Inheritance is an important principle of object oriented programming methodology. Using this principle, relation between two classes can be defined. PHP supports inheritance in its object model. PHP uses extends keyword to establish relationship between two classes.


2 Answers

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);
like image 137
Lukman Avatar answered Oct 19 '22 20:10

Lukman


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. =)

like image 42
Alix Axel Avatar answered Oct 19 '22 18:10

Alix Axel