百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>网页制作> PHP 手册中的匿名函数关联用途剖析
分享文章到:

PHP 手册中的匿名函数关联用途剖析

发布时间:09/01 来源:未知 浏览: 关键词:

匿名函数

匿名函数 也叫 闭包函数 (closures),可以创立一个没有指定名称的函数,一样作用于回调函数 (callback) 参数的值。匿名函数当前是通过 Closure 类来实现的。

1. 我们平常大概用到的相关函数举例

<?php
//array_reduce 将回调函数 callback 迭代地作用到 array 数组中的每一个单元中,从而将数组简化为简单的值。
$array = [1, 2, 3, 4];
$str = array_reduce($array, function ($return_str, $value) {
    $return_str = $return_str . $value;  //层层迭代
    return $return_str;
});
//1.第一次迭代  $return_str = '',value = '1' 返回 '1'
//2.第二次迭代  $return_str = '1',value = '2'  返回 '12'
//3.第三次迭代  $return_str = '12',value = '3'  返回 '123'
//4.第四次迭代  $return_str = '123',value = '4'  返回 '1243'
var_dump($str);
// string('12345')
// array_walk — 使用会员自定义函数对数组中的每个元素做回调处置 
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
    echo "$key. $item2<br/>\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. 实际业务用途

<?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
?>

---- 以上内容来自官方手册,可供参照

以上就是PHP 手册中的匿名函数关联用途剖析的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有150人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板