在例子中,创建两个类,一个是通用的Product类,它封装了一个产品和产品的属性,别一个是购物车的Cart类
Product类(Product.php)
02 |
protected $_partNumber,$_description,$_price; |
04 |
public function __construct($parNumber,$description,$price){ |
05 |
$this->_partNumber=$parNumber; |
06 |
$this->_description=$description; |
11 |
public function getPartNumber(){ |
12 |
return $this->_partNumber; |
15 |
public function getDescription(){ |
16 |
return $this->_description; |
19 |
public function getPrice(){ |
Cart对象(Cart.php)
01 |
require_once ('Product.php'); |
03 |
class Cart extends ArrayObject{ |
07 |
public function __construct(){ |
08 |
$this->_products=array(); |
09 |
parent::__construct($this->_products); |
12 |
public function getCarTotal(){ |
14 |
$i=$sum=0,$cnt=count($this); |
16 |
$sum+=$this[$i++]->getPrice() |
调用方法,
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