Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get visibility

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

I want to be able 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
    } 
} 
like image 921
Tiddo Avatar asked Dec 16 '22 18:12

Tiddo


1 Answers

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

To get the method visiblity, you have to use the Reflection API and check the method's modifiers

Abridged example from 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 reflecting on a class, this can be slow. You should benchmark it to see if it impacts your application too much.

like image 95
Gordon Avatar answered Jan 08 '23 10:01

Gordon