0

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?

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, do you see any more efficient way of accomplishing this, or does this look like the way to achieve what I'm trying to do?
For including a variable from the surrounding scope in an anonymous function, this is it. There may or may not be other ways of solving whatever larger picture task you're trying to accomplish of course…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.