简明现代魔法 -> PHP服务器脚本 -> PHP购物车程序设计
PHP购物车程序设计
2010-06-06
在这个程序中,创建了两个类,一个是通用的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
$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();
购物车对象是一个数组,每个数组元素装了一个商品对象,这样可以方便地计算数组内元素的总合。