作者:mobiledu2502889217 | 来源:互联网 | 2020-08-14 03:35
匿名函数也叫闭包函数(closures),可以创建一个没有指定名称的函数,一般作用于回调函数(callback)参数的值。匿名函数目前是通过Closure类来实现的。
匿名函数
匿名函数 也叫 闭包函数 (closures),可以创建一个没有指定名称的函数,一般作用于回调函数 (callback) 参数的值。匿名函数目前是通过 Closure 类来实现的。
1. 我们平时可能用到的相关函数举例
"lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2
\n";
}
echo "Before ...:\n";
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
array_walk($fruits, 'test_print');
?>
2. 实际业务用法
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
?>
---- 以上内容来自官方手册,可供参考
以上就是PHP 手册中的匿名函数关联用法分析的详细内容,更多请关注 第一PHP社区 其它相关文章!