如何检查函数是公共的还是在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);
}