4

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?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Moak
  • 12,596
  • 27
  • 111
  • 166

2 Answers2

7

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
Charles
  • 50,943
  • 13
  • 104
  • 142
  • Do I need to test whether the $method exists, or would is public be 0 if the method is undefined? – Moak Mar 24 '11 at 06:34
  • if you try to construct ReflectionMethod on a method that doesn't exist it will throw an exception. the first thing he did with `ReflectionObject` iterates thru existing methods, so thats not an issue – jon_darkstar Mar 24 '11 at 06:44
  • @Moak: You can use [`ReflectionObject::hasMethod`](http://us2.php.net/manual/en/reflectionclass.hasmethod.php) to test for method existence. This works *even for private methods* when checking outside of the class. – Charles Mar 24 '11 at 06:56
0

You should use ReflectionMethod. You can use isProtected and isPublic as well as getModifiers

http://www.php.net/manual/en/class.reflectionmethod.php http://www.php.net/manual/en/reflectionmethod.getmodifiers.php

$rm = new ReflectionMethod($this, $method); //first argument can be string name of class or an instance of it.  i had get_class here before but its unnecessary
$isPublic = $rm->isPublic();
$isProtected = $rm->isProtected();
$modifierInt = $rm->getModifiers();
$isPublic2 = $modifierInt & 256; $isProtected2 = $modifierInt & 512;

As for checking whether or not the method exists, you can do it as you do now with method_exists or just attempt to construct the ReflectionMethod and an exception will be thrown if it doesn't exist. ReflectionClass has a function getMethods to get you an array of all of a class's methods if you'd like to use that.

Disclaimer - I don't know PHP Reflection too well, and there might be a more direct way to do this with ReflectionClass or something else

jon_darkstar
  • 16,398
  • 7
  • 29
  • 37