phparraysphp-closuresaltorouter

Unexpected behaviour in PHP Altorouter when passing parameters


Setup

I'm accessing this url: <host>/render/z63034/RBLR/GLZB.

My url pattern is as such: /render/[a:title]/[a:bpFrom]/[a:bpTo].

My route gets added like so:

$router->map("GET", "/render/[a:title]/[a:bpFrom]/[a:bpTo]", function ($params) { include __DIR__ . "/views/render.php"; }, "render");

The call then looks like this:

call_user_func_array($match['target'], $match['params']);

In my index.php(where all requests are routed to) a var_dump() of $match['params'] yields the expected:

array(3) {
  ["title"]=>
  string(6) "z63034"
  ["bpFrom"]=>
  string(4) "RBLR"
  ["bpTo"]=>
  string(4) "GLZB"
}

In my render.php (which is included) a var_dump() of $params yields the unexpected

string(6) "z63034"

Question

Why is only the first element in the array I'm passing to call_user_func_array actually passed (not as an array, but just as the value itself)?


Solution

  • Notice that call_user_func_arraypasses the $params as single parameters, with this I mean, that in your function definition, you have to declare as much parameters as your $params array has.

    For example if you call this:

    $params = array('Hello', 'World');
    call_user_func_array(array($this,'test'), $params);
    

    And your function definition looks like that

     function test($a){
            echo $a; 
            echo $b; 
            echo '<br>';
        }
    

    you will only print 'Hello', so you have to declare your function like this

    function test($a, $b){
            echo $a; 
            echo $b; 
            echo '<br>';
        }
    

    Hope that helps