我试图在数组中定义PHP函数:
foreach($redirects as $from => $to) {
array_push($routes, array(
'pattern' => $from,
'action' => function($to) {
header::redirect($to, 301);
}
));
}
但我收到错误Missing argument 1 for $to
。基本上我应该在函数中定义$。我怎样才能在PHP中使用它?
答案 0 :(得分:0)
将$to
存储在数组中,然后使用call_user_func($func, $param)
调用该函数,如下所示:
foreach($redirects as $from => $to) {
array_push($routes, array(
'pattern' => $from,
'to' => $to,
'action' => function($to) {
header::redirect($to, 301);
}
));
}
称之为:
call_user_func($routes[1]['action'], $routes[1]['to']);
让我们说你的$重定向是
$redirects= ['/home' => 'index.php', 'login' => 'login.php'];
您可以将其用作:
$current_route = '/login';
foreach($routes as $index => $route) {
if($route['pattern'] == $current_route) {
call_user_func($route['action'], $routes['to']);
}
}
祝你好运!