PHP 写的一个购物车
2010-05-26 07:11 ScriptZhang 阅读(877) 评论(4) 编辑 收藏 举报在例子中,创建两个类,一个是通用的Product类,它封装了一个产品和产品的属性,别一个是购物车的Cart类
Product类(Product.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Product{ protected $_partNumber , $_description , $_price ; public function __construct( $parNumber , $description , $price ){ $this ->_partNumber= $parNumber ; $this ->_description= $description ; $this ->_price= $price ; } public function getPartNumber(){ return $this ->_partNumber; } public function getDescription(){ return $this ->_description; } public function getPrice(){ return $this ->_price; } } |
Cart对象(Cart.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | require_once ( 'Product.php' ); class Cart extends ArrayObject{ protected $_products ; public function __construct(){ $this ->_products= array (); parent::__construct( $this ->_products); } public function getCarTotal(){ for ( $i = $sum =0, $cnt = count ( $this ); $i < $cnt ; $sum += $this [ $i ++]->getPrice() ); return $sum ; } } |
调用方法,
1 2 3 4 | $cart = new Cart(); $cart []= new Product( '00231-A' , 'Description' ,1.99); $cart []= new Product( '00231-B' , 'B' ,1.99); echo $cart ->getCarTotal(); |
getCarTotal可以统计总价
得值
3.98
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步