Callback function is a very common technology in PHP programming, and it is also a problem that beginners will encounter countless times. How to use callback functions correctly can make your PHP program more flexible and intelligent.
1. What is a callback function?
Simply put, a callback function is an executable code block that can be called dynamically when needed. Originally it was mainly used for event processing, but now it is also widely used to implement template engines, data processing and other functions.
One of the benefits of callback functions is abstraction. If you want to use a simple interface to let people call the function you want to implement, you can provide an interface through the callback function and let people pass in their own implementation methods. When the program is running, your program uses the methods passed in to complete specific functions.
2. Usage scenarios of callback functions
There are many application scenarios for callback functions, which are introduced below:
The callback function in event processing can be passed as a parameter to the event processing function, which is automatically triggered when responding to the event. For example, in a PHP website, you may have a form that triggers an event when submitted. You want to write the code to process the form where the form is used. At this time, you need to encapsulate the processing code into a callback function and pass it as a parameter to the form processing function.
The callback function can also be used as a parameter of the data processing function, such as array sorting function and data filtering function. You can use callback functions to customize the way an array is sorted or to customize data filtering methods. For example, if you want to find a specific value in an array, but also want to retain the situation when multiple values are found in the array, you can write a callback function and use this function during the array search to add all matching values. Return to a new array.
Callback functions are often used in template engines to expand instructions and custom functions in templates. For example, the foreach loop syntax is used in a template to loop through the data in an array and display it in the template. The reason why the foreach syntax is supported is that a callback function is used internally to implement data traversal.
3. How to define callback functions
How to define and use callback functions in PHP? it's actually really easy. In PHP, the callback function can be either a normal function or an anonymous function.
Sample code:
<?php function my_callback_function() { echo 'Hello World!'; } call_user_func('my_callback_function'); ?>
The output of this code is: Hello World!
Sample code:
<?php $my_callback = function () { echo 'Hello World!'; }; call_user_func($my_callback); ?>
The output of this code is: Hello World!
Another more concise method is to use arrow functions.
Sample code:
<?php call_user_func(fn() => 'Hello World!'); ?>
The output result of this code is also: Hello World!
4. How to use the callback function
When using the callback function, you can use PHP's built-in functions call_user_func() and call_user_func_array().
The call_user_func() function is used to call the callback function and pass the parameters as parameters of the function. The syntax of this function is as follows:
mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
Note: The callback parameter here needs to pass the name of the callback function or the callback function stored in a variable.
Sample code:
<?php function my_callback_function($string) { echo 'Hello ' . $string . " "; } call_user_func('my_callback_function', 'World'); ?>
The output result of this code is: Hello World
.
The call_user_func_array() function is similar to the call_user_func() function, but it uses an array as a parameter of the callback function. The syntax of this function is as follows:
mixed call_user_func_array ( callable $callback , array $param_arr )
Note: The callback parameter here needs to pass the name of the callback function or the callback function stored in a variable.
Sample code:
<?php function product($a, $b) { return $a * $b; } // 回调函数作为参数 echo call_user_func_array('product', array(4, 5)) . " "; ?>
The output result of this code is: 20.
5. Application cases of callback functions
In the array function, the callback function can specify the comparison function to make the array as specified method to sort. For example, we want to arrange an array in order from small to large:
Sample code:
<?php function cmp($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } $a = array(3, 2, 5, 6, 1); usort($a, 'cmp'); print_r($a); ?>
The usort() function is used here to sort the array, where the first parameter is the Sorted array, the second parameter is the callback function.
The output result of this code is: Array ([0] => 1 [1] => 2 [2] => 3 [3] => 5 [4] => 6 ) .
In the data filtering function, the callback function can filter the data in the array according to the specified method by specifying the filtering function. For example, we want to filter out the numbers in an array:
Sample code:
<?php function is_number($var) { if (is_numeric($var)) { return true; } else { return false; } } $array = array(1, 'abc', 2, 'def', 3, 'ghi'); var_dump(array_filter($array, 'is_number')); ?>
In the above code, the array_filter() function is used, and the first parameter of the function is an array. , the second parameter is the callback function, which means that only data that meets the conditions of the is_number() function will be returned.
The output result of this code is: array(3) { [0]=> int(1) [2]=> int(2) [4]=> int(3) }.
在模板引擎中,回调函数往往用来扩充模板中的标签。例如我们现在要开发一个简单的模板引擎,实现将模板中的include标签替换为使用PHP include函数的功能:
示例代码:
<?php function replace_include($template) { $template = preg_replace_callback('#{{include file=(.*?)}}#', function($match) { return "<?php include ".trim($match[1])."; ?>"; }, $template); return $template; } $template = '{{include file="included.php"}}'; $template = replace_include($template); echo $template; ?>
在上面的代码中,使用了preg_replace_callback()函数,该函数的第一个参数为正则表达式,第二个参数回调函数。该回调函数将匹配到的值替换为PHP include函数。
该代码的输出结果为:。
The above is the detailed content of Usage of php callback function. For more information, please follow other related articles on the PHP Chinese website!