Callbacks / Callables

Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.


A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.

Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.

Пример #1 Callback function examples


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

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

// Type 1: Simple callback

// Type 2: Static class method call

// Type 3: Object method call
$obj = new MyClass();

// Type 4: Static class method call (As of PHP 5.2.3)

// Type 5: Relative static class method call (As of PHP 5.3.0)
class {
    public static function 
who() {

extends {
    public static function 
who() {

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

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

$c = new C();

Пример #2 Callback example using a Closure

// Our closure
$double = function($a) {
$a 2;

// This is our range of numbers
$numbers range(15);

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

implode(' '$new_numbers);

Результат выполнения данного примера:

 2 4 6 8 10 

Замечание: In PHP 4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.


Callback-функции, зарегистрированные такими функциями как call_user_func() и call_user_func_array(), не будут вызваны при наличии не пойманного исключения, брошенного в предыдущей callback-функции.