Callback pseudotype in PHP

Lecture



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

The PHP function is simply passed as a string of its name. You can pass any built-in or user-defined function with the exception of array () , echo () , empty () , eval () , exit () , isset () , list () , print () and unset () .

The method of the created object is transmitted as an array containing the object in the element with the index 0 and the name of the method in the element with the index 1.

Static class methods can also be passed without creating an object instance by passing the class name instead of the object name in the element with index 0.

Examples of callback functions:

<?php

// простой пример callback
function my_callback_function() {
echo 'hello world!';
}
call_user_func('my_callback_function');

// примеры callback-метода
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}

// вызов метода статического класса без создания объекта
call_user_func(array('MyClass', 'myCallbackMethod'));

// вызов метода объекта
$obj = new MyClass();
call_user_func(array(&$obj, 'myCallbackMethod'));
?>

See also: Classes and Objects in PHP


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)