In PHP, a callback is a function object/reference of a callable type; callback (or callable) variables can be used as functions, object methods and static class methods. There are many ways to implement callbacks. This article will introduce some of them. I hope they will be helpful to everyone. [Video tutorial recommendation: PHP tutorial]
1. Standard callback
Example: use call_user_func( ) function calls a function whose argument is the function name.
<?php header("content-type:text/html;charset=utf-8"); function text1(){ echo '这个是text1<br>'; }; call_user_func('text1'); ?>
Output:
这个是text1
Explanation: A call_user_func() function is called, and then the call_user_func() function calls back the text1() function during execution.
2. Static class method callback
Example: Use the call_user_func() function to call a static class method, where the parameter is a parameter containing the class name and the method to be called. array.
<?php header("content-type:text/html;charset=utf-8"); class Demo { // 用于输出字符串的函数 static function someFunction() { echo "父级函数输出 <br>"; } } class Article extends Demo { // 用于输出字符串的函数 static function someFunction() { echo "子级函数输出 <br>"; } } // 静态类方法回调 call_user_func(array('Article', 'someFunction')); call_user_func('Article::someFunction'); // 相对静态类方法回调 call_user_func(array('Article', 'parent::someFunction')); ?>
Output:
子级函数输出 子级函数输出 父级函数输出
3. Object method callback
Example: Use the call_user_func() function to call the object method, where the parameters include object variables and an array of string names of methods to be called.
<?php header("content-type:text/html;charset=utf-8"); class Demo { // 输出字符串的函数 static function someFunction() { echo "PHP中文网 <br>"; } // 输出字符串的函数 public function __invoke() { echo "__invoke()函数<br>"; } } // 类对象 $obj = new Demo(); // 对象方法调用 call_user_func(array($obj, 'someFunction')); call_user_func($obj); ?>
Output:
PHP中文网 __invoke()函数
4. Closure callback
Example: Use the array_map() function to assign valid values to the closure function Array of arguments makes a closure function callable by making a standard call or by mapping a closure function, where arguments is an array of the closure function and its valid arguments.
<?php header("content-type:text/html;charset=utf-8"); // 用于输出<br> $print_function = function($string) { echo $string."<br>"; }; // 字符串数组 $string_array = array("PHP", "Python", "MySQL"); // 可调用闭包 array_map($print_function, $string_array); ?>
Output:
PHP Python MySQL
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to implement callbacks in PHP?. For more information, please follow other related articles on the PHP Chinese website!