callback
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.
Apart from common user-defined function, create_function()
can also be used to create an anonymous callback function.
Example #1
Callback function examples
<?php
function my_callback_function() {
echo 'hello world!';
}
class MyClass {
static function myCallbackMethod() {
echo 'Hello World!';
}
}
call_user_func('my_callback_function');
call_user_func(array('MyClass', 'myCallbackMethod'));
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));
call_user_func('MyClass::myCallbackMethod');
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')); ?>
Note:
In PHP4, 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.