PHP闭包函数详解

匿名函数

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

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

rush:PHP;"> $cl = function($name){ return sprintf('hello %s',name); } echo $cli('fuck')`

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

rush:PHP;"> echo preg_replace_callback('~-([a-z])~',function ($match) { return strtoupper($match[1]); },'hello-world');`

使用use

rush: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

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 getTotal($tax){
$total = 0.0;
$callback = function($quantity,$product) use ($tax,&$total){
//constant 返回常量的值
//class返回类名
$price = constant(CLASS."::PRICE_".strtoupper($product));

  $total += ($price * $quantity)*($tax+1.0);
};
//array_walk() <a href="https://www.jb51.cc/tag/hanshu/" target="_blank" class="keywords">函数</a>对数组中的每个元素应用<a href="https://www.jb51.cc/tag/yonghu/" target="_blank" class="keywords">用户</a><a href="https://www.jb51.cc/tag/zidingyihanshu/" target="_blank" class="keywords">自定义函数</a>。在<a href="https://www.jb51.cc/tag/hanshu/" target="_blank" class="keywords">函数</a>中,数组的键名和键值是参数
array_walk($this->products,$callback);
//回调匿名<a href="https://www.jb51.cc/tag/hanshu/" target="_blank" class="keywords">函数</a>
return round($total,2);

}
}

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

print($my_cart->getTotal(0.05));

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...