Home > php教程 > php手册 > PHP简单的购物车类设计

PHP简单的购物车类设计

WBOY
Release: 2016-06-13 09:38:47
Original
869 people have browsed it

在这个程序中,创建了两个类,一个是通用的Product类,它封装了一个产品和产品的属性,另一个是购物车的Cart类。

Product类(Product.php)

商品类有三个属性,分别是编号、描述和价格。

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对象(Cart.php)

购物车类的主要功能是计算所有商品的总价格。

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

调用方法:

$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

购物车对象是一个数组,每个数组元素装了一个商品对象,这样可以方便地计算数组内元素的总合。

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template