Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php call a class method from a callback parameter

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.

like image 661
andersfylling Avatar asked Feb 02 '26 09:02

andersfylling


1 Answers

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'] ]);
like image 149
andersfylling Avatar answered Feb 05 '26 02:02

andersfylling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!