<?php function getTotal($commission) { $total = 0; // 格式: function(键值,键名)use(外部变量,&循环变量){循环变量变化程序} // 闭包内function()内变量: array_walk传的数组 在闭包里的function()参数里,变为:参数1.键值 和 参数2.键名 // 闭包内use()变量: getTotal()传进来的$commission不能直接在闭包内使用 是因为闭包例外不能共用变量 // 闭包内use()变量: 参数2的循环变量,在array_walk的过程中,随着循环未结束,也不会销毁或重置 $call_back = function ($num, $type) use ($commission,&$total) { // 各类型 的 价格 $per_type_prices = ['type_a' => 2, 'type_b' => 4, 'type_c' => 5]; $total += $num * $per_type_prices[$type] * $commission; }; // 各类型 的 数量 $nums = ['type_a' => 3, 'type_b' => 6, 'type_c' => 8]; // 此处完成遍历 array_walk($nums, $call_back); // 总手续费提成 print($total); } // 设定手续费0.22 getTotal($commission = 0.22);
php function()use(){} closure闭包
最新推荐文章于 2023-07-24 08:36:07 发布