简体   繁体   中英

Defining a PHP function dynamically

I'm trying to define a PHP function within an array:

foreach($redirects as $from => $to) {
  array_push($routes, array(
    'pattern' => $from,
    'action' => function($to) {
     header::redirect($to, 301);
    }
  ));
}

But I get an error Missing argument 1 for $to . Basically I should define $to within the function. How can I make this work in PHP?

Store $to as well in the array and use call_user_func($func, $param) to call the function as follows:

foreach($redirects as $from => $to) {
  array_push($routes, array(
    'pattern' => $from,
    'to'     => $to,
    'action' => function($to) {
     header::redirect($to, 301);
    }
  ));
}

call it as:

call_user_func($routes[1]['action'], $routes[1]['to']);

Let's say your $redirects is

$redirects= ['/home' => 'index.php', 'login' => 'login.php'];

you can use it as:

$current_route = '/login';
foreach($routes as $index => $route) {
    if($route['pattern'] == $current_route) {
        call_user_func($route['action'], $routes['to']);
    }
}

Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM