Php get visibility

Is it possible to get the visibility of methods and properties inside a class in php?

I want to do something like this:

function __call($method, $args) { if(is_callable(array($this,$method)) { if(get_visibility(array($this,$method)) == 'private') //dosomething elseif(get_visibility(array($this,$method)) == 'protected') //dosomething else //dosomething } } 
+4
source share
3 answers

To do this, you may need to use the PHP Reflection API . However, I should also ask you why you want to do this, because Reflection is usually only used in situations that are a bit hacked to begin with. Perhaps, however, like this:

 <?php class Foo { /** * * @var ReflectionClass */ protected $reflection; protected function bar( ) { } private function baz( ) { } public function __call( $method, $args ) { if( ( $reflMethod = $this->method( $method ) ) !== false ) { if( $reflMethod->isPrivate( ) ) { echo "That private.<br />\n"; } elseif( $reflMethod->isProtected( ) ) { echo "That protected.<br />\n"; } } } protected function method( $name ) { if( !isset( $this->methods[$name] ) ) { if( $this->reflect( )->hasMethod( $name ) ) { $this->methods[$name] = $this->reflect( )->getMethod( $name ); } else { $this->methods[$name] = false; } } return $this->methods[$name]; } protected function reflect( ) { if( !isset( $this->reflection ) ) { $this->reflection = new ReflectionClass( $this ); } return $this->reflection; } } $foo = new Foo( ); $foo->baz( ); $foo->bar( ); 
+6
source

is_callable takes into account visibility, but since you use it inside the class, it will always evaluate to TRUE .

To get the visibility of a method, you must use the Reflection API and check the method modifiers

A short example from the PHP manual:

 class Testing { final public static function foo() { return; } } // this would go into your __call method $foo = new ReflectionMethod('Testing', 'foo'); echo implode( Reflection::getModifierNames( $foo->getModifiers() ) ); // outputs finalpublicstatic 

The same is available for properties .

However, due to the complexity of reflection in the class, this can be slow. You should check it to see if it affects your application too much.

+7
source

This answer is a bit late, but I feel that there is still some added value, mentioning get_class_methods() in combination with method_exists() :

 <?php class Foo { // ... public function getVisibility($method) { if ( method_exists($this, $method) && in_array($method, get_class_methods($this)) ) { return 'protected or public'; } else { return 'private'; } } } 
-1
source

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


All Articles