我正在构建一个API,用户请求一个'命令',它被传递给一个类.假设该命令与PUBLIC函数匹配,它将成功执行.如果命令与PROTECTED函数匹配,则需要抛出错误.
这个想法是可以通过将函数从PUBLIC更改为PROTECTED来禁用它们,而不是重命名它们或删除它们.
我目前这样做,但是如果命令是公共的还是受保护的并不重要.
<?php
/**
* Look for Command method
*/
$sMethod = "{$sCommand}Command";
if (method_exists($this, $sMethod))
{
/**
* Run the command
*/
return $this->$sMethod($aParameters);
}
Run Code Online (Sandbox Code Playgroud)
mez*_*eze 58
只需使用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);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用is_callable函数来确定保护级别是否应该限制您:示例:
<?php
class FooBar {
protected function Foo() { return; }
public function Bar() { return; }
}
$foo = new FooBar();
var_dump(is_callable(array($foo, 'Foo')));
var_dump(is_callable(array($foo, 'Bar')));
Run Code Online (Sandbox Code Playgroud)