In this program, two classes are created, one is the generic product class, it encapsulates the properties of one product and product, and the other is the cart class of the shopping cart.
Product Class (product.php)
The commodity class has three attributes, namely, number, description, and price.
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 Object (cart.php)
The main function of the shopping cart class is to calculate the total price of all goods.
Require_once (' product.php '); class Cart extends arrayobject{protected $_products;public function __construct () {$ This->_products=array ();p arent::__construct ($this->_products);} Public Function Getcartotal () {for ( $i = $sum =0, $cnt =count ($this); $i < $cnt; $sum + = $this [$i ++]->getprice ()); return $sum;}}
Call Method:
$cart =new cart (); $cart []=new product (' 00231-a ', ' Description ', 1.99); $cart []=new product (' 00231-b ', ' B ', 1.99); echo $ Cart->getcartotal ();
The shopping Cart object is an array in which each array element is loaded with a commodity object, which makes it easy to calculate the sum of the elements within the array.
http://www.bkjia.com/PHPjc/752429.html www.bkjia.com true http://www.bkjia.com/PHPjc/752429.html techarticle in this program, two classes are created, one is the generic product class, it encapsulates the properties of one product and product, and the other is the cart class of the shopping cart. Product Class (product.php) commodity ...