Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP pass additional parameters to callback function

Tags:

php

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
      });
  }
like image 614
Tom Avatar asked Dec 23 '15 23:12

Tom


2 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();
like image 168
Tyler Sebastian Avatar answered Nov 06 '22 11:11

Tyler Sebastian


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?

like image 3
Duncan Avatar answered Nov 06 '22 12:11

Duncan