分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

PHP闭包

发布时间:2023-09-06 02:12责任编辑:蔡小小关键词:PHP闭包

1、理解闭包之前先知道一个PHP的array_walk函数

<?phpfunction myfunction($value,$key){echo "The key $key has the value $value<br>";}$a=array("a"=>"red","b"=>"green","c"=>"blue");array_walk($a,"myfunction");?>结果是:(调用了3次myfunction函数)The key a has the value redThe key b has the value greenThe key c has the value blue
<?phpclass 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)); ?????????????????//其中constant 返回 上边定义常量的值 ??????????????//跟self::访问一样,self不能再这里使用,所以用上边 ???????????????$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 ??> ???
&符号则使用变量的地址(传址)

  

 

PHP闭包

原文地址:https://www.cnblogs.com/aoxueshou/p/9547330.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved