Home >Backend Development >PHP Tutorial >PHP simple shopping cart class design_PHP tutorial
In this program, two classes are created, one is the general Product class, which encapsulates a product and product attributes, and the other is the Cart class of the shopping cart.
Product class (Product.php)
The product category 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 items.
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; } }
Calling 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, and each array element contains a product object, so that the total number of elements in the array can be easily calculated.