Tom
Tom

Reputation: 612

PHP pass additional parameters to callback function

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
      });
  }

Upvotes: 10

Views: 4015

Answers (2)

Tyler Sebastian
Tyler Sebastian

Reputation: 9458

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();

Upvotes: 4

Duncan
Duncan

Reputation: 2094

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?

Upvotes: 3

Related Questions