26

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?

3
  • Uhm, get_class_methods($class) is a way to gather an array of all public methods of a particular class... Commented Jul 20, 2012 at 8:40
  • if you want to use get_class_methods to retrieve ONLY public methods, it must used outside class.. Commented Jul 20, 2012 at 8:44
  • get_class_methods($class) returns all methods which are either public or do not have a key word. So any private methods will not be returned Commented Nov 6, 2015 at 7:59

4 Answers 4

44

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);
Sign up to request clarification or add additional context in comments.

2 Comments

i am digging the simplicity that is caused by using the statics rather than going through the instantiation of Reflectionmethod
Not the right solution: You get also the static functions.
26

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)

Comments

10

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()) {
    }
}

1 Comment

Bit of an ugly one-liner to complement your approach: array_filter(get_class_methods($this), function($v) { return (new ReflectionMethod($this, $v))->isPublic(); });
1

Have you try this way?

$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

1 Comment

I think Kristian is asking specifically for listing the public methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.