您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 邢台分类信息网,免费分类信息发布

【夯实PHP系列】购物车代码说明PHP的匿名函数

2024/5/26 1:13:21发布57次查看
【夯实php系列】购物车代码说明php的匿名函数
1. 定义:匿名函数(anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。
2. 用法:
1)作为变量的值:
闭包函数也可以作为变量的值来使用。php 会自动把此种表达式转换成内置类 closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号
2)从父作用域继承变量:
闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。
3)一个完整的例子,用购物车代码来说明:
products[$product] = $quantity; } public function getquantity($product) { return isset($this->products[$product]) ? $this->products[$product] : false; } public function gettotal($tax) { $total = 0.00; $callback = function ($quantity, $product) use ($tax, &$total) { $priceperitem = constant(__class__ . ::price_ . strtoupper($product)); $total += ($priceperitem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2);; } } $my_cart = new cart; // 往购物车里添加条目 $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); // 打出出总价格,其中有 5% 的销售税. print $my_cart->gettotal(0.05) . \n; // 最后结果是 54.29 ?>
3. 参考:
1) php官方说明 '匿名函数':http://www.php.net/manual/zh/functions.anonymous.php
2)constant() 函数返回一个常量的值: http://www.runoob.com/php/func-misc-constant.html
3) array_walk() 函数对数组中的每个元素应用用户自定义函数: http://www.w3school.com.cn/php/func_array_walk.asp
4) round() 函数对浮点数进行四舍五入:  http://www.w3school.com.cn/php/func_math_round.asp
邢台分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录