PHP 写的一个购物车
2010-05-26 07:11 ScriptZhang 阅读(876) 评论(4) 编辑 收藏 举报在例子中,创建两个类,一个是通用的Product类,它封装了一个产品和产品的属性,别一个是购物车的Cart类
Product类(Product.php)
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)
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; } }
调用方法,
$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