Find out whether the method is protected or protected

With this code I am trying to check if I can call certain functions

if (method_exists($this, $method)) $this->$method(); 

however now I want to limit execution if the $ protected method is protected, what do I need to do?

+4
source share
2 answers

You 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 the name of the class and function:

 $bar_reflect = new ReflectionMethod('Foo', 'bar'); echo $bar_reflect->isPublic(); // 1 
+7
source

You must 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 a method exists or not, you can do it, as now, using method_exists or just try to build a ReflectionMethod, and an exception will be thrown if it does not exist. ReflectionClass has a getMethods function to get an array of all class methods if you want to use this.

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

0
source

Source: https://habr.com/ru/post/1345042/


All Articles