vardius
vardius

Reputation: 6546

How to use class function as parameter in other class method

How to use class function as parametr in other class method ?

For example i have two classes A and B.

I want to use function from class B as a callback in class A.

Example:

class A {
    public function run($callback){
        call_user_func_array($callback(), [new Event()])
    }

class B {
    public function do($event){
    }
}

$a = new A();
$b = new B();
$a->run($b->do);

how can i do this correctly?

Upvotes: 2

Views: 51

Answers (2)

Carlos Mayo
Carlos Mayo

Reputation: 2114

You need to pass the callback parameter as array indicating the class and the method to execute. Also, the do method name is a reserved word, you can't use it and you have a few sintax code error. Here is the correct code:

class A {
  public function run($callback){
    call_user_func_array($callback, ['test']);
  }
}

class B {
  public function dofunc($event){
    echo $event;
  }
}

$a = new A();
$b = new B();
$a->run(array($b,'dofunc'));

Upvotes: 1

Skaza
Skaza

Reputation: 466

$callableArray = array(new B, 'do');  
if(is_callable($callableArray)) {  
    $callableArray();  
}  

Upvotes: 1

Related Questions