MIB
MIB

Reputation: 347

how to get private methods of a child by calling get_class_methods within the parent class

I'm wondering if there's a way to get this working:

<?php 
    class Foo
    {
        public function getMethods()
        {
            $methods = get_class_methods($this);
            print_r($methods);
        }
    }

    class Bar extends Foo
    {
        private function privateFunction() {}   // Not visible for parent::getMethods()
    }

    $Bar = new Bar();
    $Bar->getMethods();
?>

There's a parent class Foo, in which I've a method calling the get_class_methods($this)-Function. I'll always extend the Foo-Class by several different Bar-Classes. My problem is, that I can't see the private method privateFunction().

The goal for me would be, to see all methods of Bar but I don't want to recreate the getMethods()-Method within each of the child-classes.

So is there a way to get them within the parent-Class, or do I have to overwrite the getMethods()-Method in each child-class?

Upvotes: 1

Views: 1377

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

You probably need to use Reflection for this

class Foo {
    public function getMethods() {
        $class = new ReflectionClass($this);
        $methods = $class->getMethods(
            ReflectionMethod::IS_PUBLIC | 
            ReflectionMethod::IS_PROTECTED | 
            ReflectionMethod::IS_PRIVATE
        );
        print_r($methods);
    }
}

class Bar extends Foo {
    public function privateFunction() {}
}

$Bar = new Bar();
$Bar->getMethods();

Demo

Upvotes: 4

Related Questions