温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP手册中的匿名函数怎么用

发布时间:2020-10-10 16:58:23 来源:亿速云 阅读:94 作者:小新 栏目:编程语言

小编给大家分享一下PHP手册中的匿名函数怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

匿名函数

匿名函数 也叫 闭包函数 (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手册中的匿名函数怎么用的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI