【问题标题】:Find out whether a method is protected or public找出方法是受保护的还是公开的
【发布时间】:2011-07-21 21:19:58
【问题描述】:

我正在尝试使用此代码测试是否可以调用某些函数

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

但是现在如果 $method 受到保护,我希望能够限制执行,我需要做什么?

【问题讨论】:

    标签: php protected public-method


    【解决方案1】:

    你会想要使用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";
    }
    

    输出:

    bar: Public
    baz: Protected
    qux: Private
    

    你也可以通过类和函数名来实例化 ReflectionMethod 对象:

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

    【讨论】:

    • 我是否需要测试 $method 是否存在,或者如果方法未定义,是否 public 为 0?
    • 如果你试图在一个不存在的方法上构造 ReflectionMethod ,它会抛出一个异常。他对ReflectionObject 所做的第一件事是遍历现有方法,所以这不是问题
    • @Moak:您可以使用ReflectionObject::hasMethod 来测试方法是否存在。在类外检查时,这甚至对于私有方法也有效。
    【解决方案2】:

    你应该使用反射方法。您可以使用isProtectedisPublic 以及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;
    

    至于检查方法是否存在,你可以像现在method_exists那样做,或者只是尝试构造ReflectionMethod,如果不存在就会抛出异常。 ReflectionClass 有一个函数 getMethods 可以为你提供一个包含所有类方法的数组,如果你想使用它的话。

    免责声明 - 我不太了解 PHP 反射,可能有更直接的方法可以使用 ReflectionClass 或其他方法来完成此操作

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 2013-08-14
      • 1970-01-01
      • 2012-05-31
      • 2013-06-24
      • 2011-10-11
      • 2010-10-21
      • 2018-01-05
      • 2019-07-12
      相关资源
      最近更新 更多