如何检查函数是公共的还是在PHP中受保护的 [英] How to check if a function is public or protected in PHP

查看:75
本文介绍了如何检查函数是公共的还是在PHP中受保护的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个API,用户可以在其中请求命令",该命令将传递到类中.假设命令与PUBLIC函数匹配,它将成功执行. 如果该命令与PROTECTED函数匹配,则需要引发错误.

I am building an API where the user requests a 'command', which is passed into a class. Assuming the command matches a PUBLIC function, it will execute successfully. If the command matches a PROTECTED function, it needs to throw an error.

想法是可以通过将功能从PUBLIC更改为PROTECTED来禁用它们,而不是重命名或删除它们.

The idea is that functions can be disabled by changing them from PUBLIC to PROTECTED, rather than renaming them or removing them.

我目前正在执行此操作,但是该命令是公共命令还是受保护的命令都没关系.

I currently do this, but it doesn't matter if the command is public or protected.

<?php
/**
 * Look for Command method
 */
$sMethod = "{$sCommand}Command";
if (method_exists($this, $sMethod))
{
    /**
     * Run the command
     */
    return $this->$sMethod($aParameters);
}

推荐答案

只需使用 ReflectionMethod :

/**
 * Look for Command method
 */
if (method_exists($this, $sMethod))
{
    $reflection = new ReflectionMethod($this, $sMethod);
    if (!$reflection->isPublic()) {
        throw new RuntimeException("The called method is not public.");
    }
    /**
     * Run the command
     */
    return $this->$sMethod($aParameters);
}

这篇关于如何检查函数是公共的还是在PHP中受保护的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆