从PHP 5.3开始新增了匿名函数(Anonymous functions),也叫闭包函数(closures),关键字 use 同时也在匿名函数中。
先看一下匿名函数的示例,作为回调函数的参数:
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// 输出 helloWorld
?>
匿名函数也可以作为变量的值来使用。把一个匿名函数赋值给一个变量的方式和普通变量赋值的语法是一样的,最后也需要加上分号。
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
匿名函数不会自动从父作用域中继承变量,注意从父作用域继承变量和使用全局变量是不同的。如果父作用域本身就是全局的 情况下就不存在从父作用域继承变量了,如果不是全局的话,想要使用父作用域中的变量,必须在声明匿名函数时候使用use换键字 来定义继承父作用域的变量。
<?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";
// The result is 54.29
?>
匿名函数(闭包函数)是一个独立的命名空间,你不能访问这个命名空间之外的变量,使用use关键字可以把外部的变量 带到这个命名空间中。可以通过使用 & 符号来声明指针变量。
(End)
Learn how to market your app with practical tips how to increase mobile app downloads and best aso services. Increase app downloads and drive engagement with targeted campaigns. Tapaso is always your best choice! ,how to increase mobile app downloads;