Search code examples
phpprotectedpublic-method

Find out whether a method is protected or public


With this code I'm trying to test if I can call certain functions

if (method_exists($this, $method))
    $this->$method();

however now I want to be able to restrict the execution if the $method is protected, what would I need to do?


Solution

  • You'll want to use Reflection.

    class Foo { 
        public function bar() { } 
        protected function baz() { } 
        private function qux() { } 
    }
    $f = new Foo();
    $f_reflect = new ReflectionObject($f);
    foreach($f_reflect->getMethods() as $method) {
        echo $method->name, ": ";
        if($method->isPublic()) echo "Public\n";
        if($method->isProtected()) echo "Protected\n";
        if($method->isPrivate()) echo "Private\n";
    }
    

    Output:

    bar: Public
    baz: Protected
    qux: Private
    

    You can also instantiate the ReflectionMethod object by class and function name:

    $bar_reflect = new ReflectionMethod('Foo', 'bar');
    echo $bar_reflect->isPublic(); // 1