Home > Backend Development > PHP Tutorial > PHP simple shopping cart class design_PHP tutorial

PHP simple shopping cart class design_PHP tutorial

WBOY
Release: 2016-07-13 10:33:39
Original
955 people have browsed it

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;
   	}
}
Copy after login

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;
	}
}
Copy after login

Calling method:

$cart=new Cart();
$cart[]=new Product('00231-A','Description',1.99);
$cart[]=new Product('00231-B','B',1.99);
echo $cart->getCarTotal();
Copy after login

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752429.htmlTechArticleIn this program, two classes are created, one is the general Product class, which encapsulates a product and The attributes of the product, and the other is the Cart class of the shopping cart. Product class (Product.php) Product...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template