MultiDev
MultiDev

Reputation: 10649

PHP: Storing callback functions with arguments on array

I am writing a simple router class which would allow you to execute a function when a route match is found. So, when you are defining routes, you would do something like this:

$message = 'Good morning!';

$router->addRoute('GET', 'welcome', function($message) {
    echo $message;
});

Then, in the router class, this gets added to an array like:

public function addRoute($method, $pattern, $handler) {
    $this->routes[$pattern] = ['method' => $method, 'handler' => $handler];
}

Once a match is found by comparing the pattern with the requested URL, I have:

return call_user_func($setting['handler']);

This gives me an error: Fatal error: Uncaught ArgumentCountError: Too few arguments to function

...so I tried using:

return call_user_func_array($setting['handler'], array($message));

...but this gives me: Notice: Undefined variable: message

How can I pass a function (including arguments, if existing) to execute within the router class using values stored on an array?

Upvotes: 0

Views: 187

Answers (1)

deceze
deceze

Reputation: 522145

If you don't want to pass $message as an argument at call time, it should not be in the function parameter list. You're probably just looking to use the variable from the surrounding scope:

$message = 'Good morning!';

$router->addRoute('GET', 'welcome', function () use ($message) {
    echo $message;
});

Upvotes: 2

Related Questions