Checking method visibility in PHP

强颜欢笑 提交于 2019-12-10 04:04:27

问题


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;
}


来源:https://stackoverflow.com/questions/2981622/checking-method-visibility-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!