1

How to pass method callback as a parameter to another method? All the examples I've seen use functions, but not methods. What I've tried is:

call_user_func($this, 'method_name', [$param1, $param2,...]); 

Also is there another, more elegant way, like just passing $this->method_name as a parameter?

I know I could add the callback as:

function () use ($param1, $param2,...) { return $this->method_name($param1, $param2); } 

But I would like to omit the closure part.

1 Answer 1

1

You could also use [$obj, 'method'] as an callback, bind to an object.

class A { public $b = 'test'; public function callback() { echo $this->b; } } $a = new A(); $f = [$a, 'callback']; $f(); 
Sign up to request clarification or add additional context in comments.

2 Comments

I have a private constructor with arguments, so I can't make an instance by calling default constructor. Also, I'm calling this callback inside of the same class, so could the instance initialization be replaced with $this or something?
Tested it: yes, you can use $this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.