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).
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.
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.
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.
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.
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);
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. =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With