10

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
      });
  }
2
  • I don't really see through what you want to do? Should that be pseudo code above or what does calling looks like? Commented Dec 23, 2015 at 23:28
  • I added an example of what I want to achieve with a closure but how would I do it by using a class method instead. Commented Dec 23, 2015 at 23:43

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

5 Comments

Would $data be defined since calling() is providing it?
@Tom I provided a complete example
That would work but I can't edit mDo method. I provided an example of what I want to achieve using a closure but I need to use the class method instead.
Seemed like overkill for my use case.
I don't see why you need to use reflection - seems like overkill.
3

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.