Home » Php » PHP pass additional parameters to callback function

PHP pass additional parameters to callback function

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there a way to pass additional parameters to a callback function?

class Bar{

  public function test(){
      $count = 0; 

      $foo = new Class();
      $foo->calling([$this, 'barFunction']);
  }

  public function barFunction($data, $count){
      //...
  }

I want Foo’s calling method to pass data in and to also pass $count as the second parameter.

Here is an example with a closure instead of a parameter. If I use a closure I can pass $count in but in this case I need to use Bar’s class function.

class Bar{

  public function test(){
      $count = 0; 

      $foo = new Class();
      $foo->calling(function($data) use($count){
         //..some work
      });
  }
How to&Answers:

Could use call_user_func_array

call_user_func_array([$context, $function], $params);

i.e. in your example, $context would be Bar ($this), $function would be your 'barFunction', and the params would be [$data, $count].

Like this?

<?php 

class Foo {
    public function __construct() {}

    public function mDo($callback) {
        $count = 10;
        $data = ['a', 'b'];

        // do a lot of work (BLOCKING)

        call_user_func_array($callback, [$data, $count]);
    }
}

class Bar {
    public function test() {
        $a = new Foo();
        $a->mDo([$this, 'callback']);
    }

    public function callback($data, $count) {
        print($data);
        print($count);
    }
}

$bar = new Bar();
$bar->test();

Answer:

OOP is your friend. Declare the callback as a class:

class BarCallback {
    private $count;

    public function __construct($count) {
        $this->count = $count;
    }

    public function callback($data) {
        // do work here
    }
}

And then Bar would look something like this:

class Bar {
  public function test() {
      $count = 0; 

      $foo = new Class();
      $bar_cb = new BarCallback($count);
      $foo->calling([$bar_cb, 'callback']);
  }
}

Does that help?