4

From Class A I want to implement a callback that includes specific methods as parameters. Eg.

    call_user_func_array($callback, ['$this->get', '$this->post']);

However this doesn't work. What I am aiming for here is to do this:

index.php

    $API = new API();
    $API->state('/users', function ($get, $post) {
        $get('/', 'UserController.getAll');
    });

API.php

    public function state ($state, $callback) {
        call_user_func_array($callback, ['$this->get', '$this->post']);
    }

    public method get ($uri, $ctrl)  { echo 'getting'; }
    public method post ($uri, $ctrl) { echo 'posting'; }

Thanks for any input! I do realize using $this->method, won't work as $this-> will not exist within the callback scope.

1
  • My PHP version is 5.5.12 Commented Jan 30, 2016 at 18:08

3 Answers 3

1

I found out that i somehow had to bind $this to the correct scope. I managed to do that by including $this (the class instant) with each parameter:

call_user_func_array($callback, [ [$this, 'get'] ]);
Sign up to request clarification or add additional context in comments.

Comments

0

because you are using object methods and not global functions as callback, you must use call_user_method_array instead of call_user_func_array.

5 Comments

This will give me the comment: only variables can be passed back as parameters. After reading about it i can see this is deprecated, and completely removed in php 7
call_user_method_array is deprecated since PHP 4.1.0 and was removed with PHP 7.
As i see in the php documentation, call_user_method_array is deprecated; you should use call_user_func_array(array($this, $callback), $params); now.
You should read the docs again, the first parameter should be a callable variable. not an array.
Now I feel pretty stupid, what I should have said was: "i get the error: () expects parameter 1 to be a valid callback, second array member is not a valid method"
0

If you need access to only public members and methods then one possible solution can be this:

class API{
  public function state ($state, $callback) {
      call_user_func($callback, $this);
  }

  public function get ($uri, $ctrl)  { echo 'getting'; }
  public function post ($uri, $ctrl) { echo 'posting'; }
}

$API = new API();
$API->state('/users', function ($context) {
    $context->get('/', 'UserController.getAll');
});

1 Comment

If i wanted to do that, it would be easier to just add the $API into the function scope rather than including the this variable from within the class scope itself.

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.