您的位置:首页 > 编程语言 > PHP开发

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

2016-09-22 23:10 316 查看
1. 定义:匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

2. 用法:

  1)作为变量的值

    闭包函数也可以作为变量的值来使用。PHP 会自动把此种表达式转换成内置类 Closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号

  2)从父作用域继承变量

    闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。

  3)一个完整的例子,用购物车代码来说明:

<?php
// 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。
// 其中有一个方法用来计算购物车中所有商品的总价格,该方法使
// 用了一个 closure 作为回调函数。
class Cart
{
const PRICE_BUTTER  = 1.00;
const PRICE_MILK    = 3.00;
const PRICE_EGGS    = 6.95;

protected   $products = array();

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.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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: