Checking method visibility in PHP

2019-04-27 03:45发布

问题:

Is there any way of checking if a class method has been declared as private or public?

I'm working on a controller where the url is mapped to methods in the class, and I only want to trigger the methods if they are defined as public.

回答1:

You can use the reflection extension for that, consider these:

ReflectionMethod::isPrivate
ReflectionMethod::isProtected
ReflectionMethod::isPublic
ReflectionMethod::isStatic



回答2:

To extend Safraz Ahmed's answer (since Reflection lacks documentation) this is a quick example:

class foo {
    private function bar() {
        echo "bar";
    }
}

$check = new ReflectionMethod('foo', 'bar');

echo $check->isPrivate();


回答3:

Lets look from other side. You don't really need to know method's visibility level. You need to know if you can call the method. http://lv.php.net/is_callable

if(is_callable(array($controller, $method))){
  return $controller->$method();
}else{
  throw new Exception('Method is not callable');
  return false;
}