Home >Backend Development >PHP Tutorial >Detailed explanation of callback functions and anonymous functions in PHP
Some functions such as call_user_func() or usort() can accept user-defined callback functions as parameters. The callback function can not only be a simple function, but also an object method, including static class methods.
To put it simply, the parameters of a function are also a function.
Anonymous function definition:
Anonymous functions (Anonymous functions), also called closures, allow temporary creation of a function without a specified name. The value most commonly used as a callback function argument. Of course, there are other applications as well.
Simply put, it is a function without a function name
<?phpclass Product{ public $name; public $price; //存储各种回调函数 private $callbacks; public function __construct($name,$price) { $this->name=$name; $this->price=$price; } //注册回调函数 function registerCallBack($callback) { $this->callbacks[]=$callback; } //执行回调函数 function sale() { echo "$this->name 开始执行促销信息 $this->price \n"; foreach($this->callbacks as $callback) { //执行回调函数 $this->price=call_user_func($callback,$this->name,$this->price); } echo "$this->name 促销执行完毕 $this->price \n"; } }//提供回调函数class Sale{ function sale1(){ //返回匿名函数 各种促销 return function($name,$price){ $price-=5; echo "$name 美女,减5元 变为 $price\r\n"; return $price; }; } function sale2(){ return function($name,$price){ $price-=3; echo "$name 随便卖,减3元 变为 $price \r\n"; return $price; }; } }$p=new Product("足球",50);$sale =new Sale();$p->registerCallBack($sale->sale1());$p->registerCallBack($sale->sale2());$p->sale();
Related recommendations:
Analysis of PHP callback function
javascript The meaning of the callback function
Detailed explanation of the usage of the callback function of the php custom function
The above is the detailed content of Detailed explanation of callback functions and anonymous functions in PHP. For more information, please follow other related articles on the PHP Chinese website!