如何在控制器中获取所有 public 函数方法?
How I can grab all public function methods in a controller?
我使用 __remap()
函数来避免任何未定义的方法并使其重定向到 index() 函数。
function __remap($method)
{
$array = {"method1","method2"};
in_array($method,$array) ? $this->$method() : $this->index();
}
该函数将检查是否不是 method1 和 method2.. 它将重定向到索引函数。
现在,如何自动获取该控制器中的所有 public 函数 方法,而不是手动放入 $array
变量?
您需要测试方法是否存在并且是 public。所以你需要使用反射和方法存在。像这样:
function __remap($method)
{
if(method_exists($this, $method)){
$reflection = new ReflectionMethod($this, $method);
if($reflection->isPublic()){
return $this->{$method}();
}
}
return $this->index();
}
或者您可以使用 get_class_methods() 创建方法数组
好吧,我很无聊:
$r = new ReflectionClass(__CLASS__);
$methods = array_map(function($v) {
return $v->name;
},
$r->getMethods(ReflectionMethod::IS_PUBLIC));
我修改了代码变成了这样
function _remap($method)
{
$controllers = new ReflectionClass(__CLASS__);
$obj_method_existed = array_map(function($method_existed)
{
return $method_existed;
},
$controllers->getMethods(ReflectionMethod::IS_PUBLIC));
$arr_method = array();
//The following FOREACH I think was not good practice.
foreach($obj_method_existed as $method_existed):
$arr_method[] = $method_existed->name;
endforeach;
in_array($method, $arr_method) ? $this->$method() : $this->index();
}
任何增强而不是使用 foreach?
我使用 __remap()
函数来避免任何未定义的方法并使其重定向到 index() 函数。
function __remap($method)
{
$array = {"method1","method2"};
in_array($method,$array) ? $this->$method() : $this->index();
}
该函数将检查是否不是 method1 和 method2.. 它将重定向到索引函数。
现在,如何自动获取该控制器中的所有 public 函数 方法,而不是手动放入 $array
变量?
您需要测试方法是否存在并且是 public。所以你需要使用反射和方法存在。像这样:
function __remap($method)
{
if(method_exists($this, $method)){
$reflection = new ReflectionMethod($this, $method);
if($reflection->isPublic()){
return $this->{$method}();
}
}
return $this->index();
}
或者您可以使用 get_class_methods() 创建方法数组
好吧,我很无聊:
$r = new ReflectionClass(__CLASS__);
$methods = array_map(function($v) {
return $v->name;
},
$r->getMethods(ReflectionMethod::IS_PUBLIC));
我修改了代码变成了这样
function _remap($method)
{
$controllers = new ReflectionClass(__CLASS__);
$obj_method_existed = array_map(function($method_existed)
{
return $method_existed;
},
$controllers->getMethods(ReflectionMethod::IS_PUBLIC));
$arr_method = array();
//The following FOREACH I think was not good practice.
foreach($obj_method_existed as $method_existed):
$arr_method[] = $method_existed->name;
endforeach;
in_array($method, $arr_method) ? $this->$method() : $this->index();
}
任何增强而不是使用 foreach?