cantera
cantera

Reputation: 25015

Pass Method/Function as Argument and Invoke

How can I pass a method as an argument to a function so it can be invoked from the function?

I'm trying to pass the Slim Framework's redirect() method from a route handler to an object method that handles the redirect logic:

$app->get('/contact', function() use ($app) {
  $obj = new Obj;
  $obj->handle_request($app->redirect);
});

And then in the object method:

public function handle_request(callable $redirect) {
  $redirect('/about');
}

That gives me this error: Argument 1 passed to Obj::handle_request() must be callable, null given

If I do the same thing without the callable type hint, I get this error: Function name must be a string

Upvotes: 1

Views: 654

Answers (2)

Rhumborl
Rhumborl

Reputation: 16609

You are using the callable hint incorrectly. As per the docs:

A PHP function is passed by its name as a string.

...

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

So in your case, you need to pass it as array($app, 'redirect'):

$app->get('/contact', function() use ($app) {
    $obj = new Obj;
    $obj->handle_request(array($app, 'redirect'));
});

However in your case, as other answers have stated, unless you are doing more than just calling redirect in handle_request or have a particular requirement to pass a callback in this way, you are probably better off just passing $app to handle_request and letting that do what it needs with $app itself. This is a better OO pattern.

Upvotes: 2

undefined
undefined

Reputation: 4135

You can just pass the $app object and then call the redirect method from there.

Example

$app->get('/contact', function() use ($app) {
  $obj = new Obj;
  $obj->handle_request($app);
});

public function handle_request($app) {
  $app -> redirect('/about');
}

Hope this helps :)

Upvotes: 1

Related Questions