views:

78

answers:

3

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.

+7  A: 

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

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

Sarfraz
Perfect, thanks!For others, also not familiar with the ReflectionMethod, this is how it's used: `$methodReflection = new ReflectionMethod('some_class', 'some_method');` `if($methodReflection->isPublic()) { /* do whatever */ }`
phobia
You'd also probably (maybe) want to check for final/static/abstract too.
salathe
+4  A: 

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();
kemp
That's good addition, +1 :)
Sarfraz
+1  A: 

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;
}
Anpher
This is the most natural solution yet provided.
erisco
yes, very good suggestion. The issue is though that all method are inside the current class, so they will all be callable, private or public, so I'm sort of creating my own visibility here by only alowing to run public methods from the url. But a part of the story is also that I discovered that `__destruct` and such needs to be public, and was therefore callable by url, so now I've gone for a combo with a method prefix (action_).
phobia