[英]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以外的其他內容。它將重定向到索引函數。
現在,如何才能自動獲取該控制器中的所有公共函數方法,而不是手動放置$array
變量?
您需要測試method是否存在並且是公共的。 因此,您需要使用反射和方法存在。 像這樣:
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 ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.