代码改变世界

PHP 写的一个购物车

  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

 

点击右上角即可分享
微信分享提示