With this code I'm trying to test if I can call开发者_如何学JAVA 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?
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
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
精彩评论