博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

PHP 写的一个购物车

Posted on 2010-05-26 08:38  gzlxm  阅读(281)  评论(0)    收藏  举报

在例子中,创建两个类,一个是通用的Product类,它封装了一个产品和产品的属性,别一个是购物车的Cart类 

Product类(Product.php)

01 class Product{
02    protected $_partNumber,$_description,$_price;
03      
04    public function __construct($parNumber,$description,$price){
05       $this->_partNumber=$parNumber;
06       $this->_description=$description;
07       $this->_price=$price;
08       
09    }
10      
11    public function getPartNumber(){
12     return $this->_partNumber;
13    }
14      
15    public function getDescription(){
16     return $this->_description;
17    }
18      
19    public function getPrice(){
20     return $this->_price;
21    }
22 }

 

Cart对象(Cart.php)

01 require_once ('Product.php');
02   
03 class Cart extends ArrayObject{
04       
05     protected $_products;
06       
07     public function __construct(){
08         $this->_products=array();
09         parent::__construct($this->_products);
10     }
11       
12     public function getCarTotal(){
13         for(
14           $i=$sum=0,$cnt=count($this);
15           $i<$cnt;
16           $sum+=$this[$i++]->getPrice()
17         );
18         return $sum;
19     }
20       
21 }

 

调用方法,

1 $cart=new Cart();
2 $cart[]=new Product('00231-A','Description',1.99);
3 $cart[]=new Product('00231-B','B',1.99);
4 echo $cart->getCarTotal();

 

getCarTotal可以统计总价

得值

3.98

 

转自:http://www.cnblogs.com/ScriptZhang/archive/2010/05/26/1743884.html