0

Let's say javascript simple callback function could look like that:

function foo(test, clb) {
   clb(test);
}
foo("aaa", function(e) {
   console.log(e);
});

//Found solution:
function processSomething($arr, callable $callback) {
   $callback($arr);
}

processSomething("xx", function($d) {
   echo $d;
});
Mark Rune
  • 37
  • 5

2 Answers2

0
$callback = function(){
   return 'something';
};

function myFunc($param1, $param2, $callback) {
   $data = $param1 + $param2; // or whatever you want to do
   $callback($data);  // call the callback function
}

//Thanks, just did it like that:

function processSomething($arr, callable $callback) {
   $callback($arr);
}
processSomething("xx", function($d) {
   echo $d;
});
Mark Rune
  • 37
  • 5
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
0

Yes, but maybe not the way your used to. The following code if from the PHP manual

<?php

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function');

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}

class B extends A {
    public static function who() {
        echo "B\n";
    }
}

call_user_func(array('B', 'parent::who')); // A

// Type 6: Objects implementing __invoke can be used as callables (since PHP 5.3)
class C {
    public function __invoke($name) {
        echo 'Hello ', $name, "\n";
    }
}

$c = new C();
call_user_func($c, 'PHP!');
?>

A simpler example would be:

<?php
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

Source and more examples can be found here: PHP Manual Callbacks/Callables

thatguy
  • 1,249
  • 9
  • 26