php5.3 引用了 闭包。也就是匿名函数。
用法:
1、可以负值 并调用
<?php
$name = function($str){
echo $str;
};
$name('Hello World!');
?>
直接输出 Hello World!
2、用 use() 从父作用域继承变量
<?php
$message = 'hello';
// 没有 "use"
$example = function () {
var_dump($message);
};
$example();
?>
运行这段代码,会报
Notice: Undefined variable:
//有 “use”
<?php
$message = 'hello';
$example = function () use($message){
var_dump($message);
};
$example();
?>
输出 hello。 这个时候,闭包里不能更改原参数,只是引用了原参数的复制版本。
<?php
$message = 'hello';
$example = function () use($message){
$message ='world';
};
$example();
echo $message;
?>
输出 hello
3、用use 通过引用 继承父作用域 的参数。
<?php
$message = 'hello';
$example = function () use(&$message){
$message ='world';
};
$example();
echo $message;
?>
输出 world
4、如果需要规定函数返回类型,在use() 后面加上返回类型
<?php
$message = 'hello';
$example = function () use($message):string{
return $message;
};
$example();
?>
5、用闭包做购物车计算所有商品总价格,省去 foreach 遍历循环
class Cart
{
//商品
const PRICE_BUTTER = 1.0;
const PEICE_MILK = 3;
const PEICE_EGGS = 6.95;
protected $products = [];
//添加商品,和商品库存函数
public function add($product,$quantity)
{
$this->products[$product] = $quantity;
}
//获取商品库存函数
public function getQuatity($product)
{
return isset($this->products[$product])??FALSE;
}
//计算总价函数
public function getTotal($tax=0)
{
$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); //改方法,分别将数组的values和key 交给后。 面的函数处理
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