PHP   发布时间:2019-11-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了PHP闭包函数详解大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

匿名函数

也叫闭包函数(closures允许创建一个没有指定没成的函数,最经常用作回调函数参数的值。

闭包函数没有函数名称,直接在function()传入变量即可 使用时将定义的变量当作函数来处理

php;"> $cl = function($Name){ return sprintf('Hello %s',Name); } echo $cli('fuck')`

直接通过定义为匿名函数的变量名称来调用

php;"> echo preg_replace_callBACk('~-([a-z])~',function ($match) { return strtoupper($match[1]); },'Hello-world');`

使用use

php;"> $message = 'Hello'; $example = function() use ($messagE){ var_dump($messagE); }; echo $example(); //输出Hello $message = 'world'; //输出Hello 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候 echo $example(); //重置为Hello $message = 'Hello'; //此处传引用 $example = function() use(&$messagE){ var_dump($messagE); }; echo $example(); //输出Hello $message = 'world'; echo $example(); //此处输出world //闭包函数也用于正常的传值 $message = 'Hello'; $example = function ($data) use ($messagE){ return "{$data},{$messagE}"; };

echo $example('world');

example

php;"> class Cart{ //在类里面定义常量用 const 关键字,而不是通常的 define() 函数。 const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.00; const PRICE_EGGS = 6.95;

protected $products = [];
public function add($product,$quantity){
$this->products[$product] = $quantity;
}
public function getQuantity($product){
//是否定义了
return isset($this->products[$product])?$this->products[$product]:falSE;
}
public function get@R_219_10586@l($taX){
$@R_219_10586@l = 0.0;
$callBACk = function($quantity,$product) use ($tax,&$@R_219_10586@l){
//constant 返回常量的值
//class返回类名
$price = constant(CLASS."::PRICE_".strtoupper($product));

  $@R_219_10586@l += ($price * $quantity)*($tax+1.0);
};
//array_walk() 函数对数组中的每个元素应用用户自定义函数。在函数中,数组的键名和键值是参数
array_walk($this->products,$callBACk);
//回调匿名函数
return round($@R_219_10586@l,2);

}
}

$my_cart = new Cart();
$my_cart->add('butter',1);
$my_cart->add('milk',3);
$my_cart->add('eggs',6);

print($my_cart->get@R_219_10586@l(0.05));

以上就是关于php闭包函数的相关内容,希望对大家的学习有所帮助。

大佬总结

以上是大佬教程为你收集整理的PHP闭包函数详解全部内容,希望文章能够帮你解决PHP闭包函数详解所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。