In this example, two classes are created. One is a common product class, which encapsulates the attributes of a product and a product, and the other is the cart class of the shopping cart.
Product class (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 object (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() |
Call method,
2 |
$cart[]=new Product('00231-A','Description',1.99); |
3 |
$cart[]=new Product('00231-B','B',1.99); |
4 |
echo $cart->getCarTotal(); |
Getcartotal can calculate the total price
Value
3.98
From: http://www.cnblogs.com/ScriptZhang/archive/2010/05/26/1743884.html