Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to list out all public functions of class

Tags:

php

class

I've heard of get_class_methods() but is there a way in PHP to gather an array of all of the public methods from a particular class?

like image 609
Kristian Avatar asked Jul 20 '12 08:07

Kristian


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.

How to declare public function in PHP?

public - the property or method can be accessed from everywhere. This is default. protected - the property or method can be accessed within the class and by classes derived from that class. private - the property or method can ONLY be accessed within the class.

What is __ method __ in PHP?

"Method" is basically just the name for a function within a class (or class function). Therefore __METHOD__ consists of the class name and the function name called ( dog::name ), while __FUNCTION__ only gives you the name of the function without any reference to the class it might be in.


3 Answers

Yes you can, take a look at the reflection classes / methods.

http://php.net/manual/en/book.reflection.php and http://www.php.net/manual/en/reflectionclass.getmethods.php

$class = new ReflectionClass('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);
var_dump($methods);
like image 136
Alex Barnes Avatar answered Oct 02 '22 19:10

Alex Barnes


As get_class_methods() is scope-sensitive, you can get all the public methods of a class just by calling the function from outside the class' scope:

So, take this class:

class Foo {
    private function bar() {
        var_dump(get_class_methods($this));
    }

    public function baz() {}

    public function __construct() {
        $this->bar();
    }
}

var_dump(get_class_methods('Foo')); will output the following:

array
  0 => string 'baz' (length=3)
  1 => string '__construct' (length=11)

While a call from inside the scope of the class (new Foo;) would return:

array
  0 => string 'bar' (length=3)
  1 => string 'baz' (length=3)
  2 => string '__construct' (length=11)
like image 22
Diego Agulló Avatar answered Oct 02 '22 18:10

Diego Agulló


After getting all the methods with get_class_methods($theClass) you can loop through them with something like this:

foreach ($methods as $method) {
    $reflect = new ReflectionMethod($theClass, $method);
    if ($reflect->isPublic()) {
    }
}
like image 30
Adi Avatar answered Oct 02 '22 18:10

Adi