php获得可见性

Tid*_*ddo 4 php visibility access-modifiers

是否有可能在php中获取类中方法和属性的可见性?

我希望能够做到这样的事情:

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
    } 
} 
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 7

is_callable将可见性考虑在内,但由于您在课堂内使用它,因此它总是会评估为TRUE.

要获得方法可见性,您必须使用Reflection API并检查方法的修饰符

PHP手册中的简要例子:

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
Run Code Online (Sandbox Code Playgroud)

这同样适用于性能.

但是,由于反映在课堂上的复杂性,这可能很慢.您应该对其进行基准测试,以确定它是否会对您的应用程


Ber*_*rak 6

您可能需要考虑使用PHP的Reflection API.但是,我也应该问你为什么要这样做,因为Reflection通常只会在开始时有点hacky的情况下使用.虽然有可能,所以这里是:

<?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's private.<br />\n";
            }
            elseif( $reflMethod->isProtected( ) ) {
                echo "That's 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( );
Run Code Online (Sandbox Code Playgroud)

  • 尽管您认为海报所做的事情可能是个坏主意,但仍然回答了 +1。 (2认同)