Callbacks / CallablesCallbacks 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. PassingA 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. Accessing protected and private methods from within a class is allowed. 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.
Example #1 Callback function examples
<?php
Example #2 Callback example using a Closure
<?php The above example will output: 2 4 6 8 10
|