dannyvankooten / AltoRouter

PHP routing class. Lightweight yet flexible. Supports REST, dynamic and reversed routing.
https://dannyvankooten.github.io/AltoRouter/
MIT License
1.22k stars 231 forks source link

PHP 8+ Fatal error: Uncaught Error: Unknown named parameter #277

Open luigif opened 1 year ago

luigif commented 1 year ago

In PHP 8+ when processing requests using call_user_func_array (as in http://altorouter.com/usage/processing-requests.html)

// call closure or throw 404 status
if( is_array($match) && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] ); 
} else {
    // no route was matched
    header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

a fatal error is generated if $match['params'] key values do not match with function $match['target'] parameters name.

A quick solution is to extract array values with:

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

since according to the manual page (https://www.php.net/manual/en/function.call-user-func-array.php):

If the keys of args are all numeric, the keys are ignored and each element will be passed to callback as a positional argument, in order.
If any keys of args are strings, those elements will be passed to callback as named arguments, with the name given by the key. 

The example should include some documentation to explain this issue that is very hard to track and debug when upgrading from php < 8.

o-kamalGit commented 3 months ago

Hi, This is correct. I'm using the latest version 2.0.6 with a code created 5 year ago and I faced this issue. Glad that someone solved it. It should be added to the next version release to not break old code compatibility. Thank you.