加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 查明方法是受保护还是公开

发布时间:2020-12-13 17:37:33 所属栏目:PHP教程 来源:网络整理
导读:使用此代码我试图测试是否可以调用某些函数 if (method_exists($this,$method)) $this-$method(); 但是现在我希望能够限制执行,如果$方法受到保护,我还需要做什么? 解决方法 你会想要使用 Reflection. class Foo { public function bar() { } protected fun
使用此代码我试图测试是否可以调用某些函数

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

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

解决方法

你会想要使用 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 "Publicn";
    if($method->isProtected()) echo "Protectedn";
    if($method->isPrivate()) echo "Privaten";
}

输出:

bar: Public
baz: Protected
qux: Private

您还可以按类和函数名实例化ReflectionMethod对象:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读