PHP simple shopping cart design _ PHP Tutorial

Source: Internet
Author: User
PHP simple shopping cart design. In this program, two classes are created. one is a common Product class, which encapsulates the attributes of one Product and one Product, and the other is the Cart class of the shopping Cart. Product class (Product. php) the Product creates two classes in this program. 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)

The product category has three attributes: ID, 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;}}

Call method:

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

A shopping cart object is an array. each array element contains a commodity object. This allows you to conveniently calculate the sum of elements in the array.

Bytes. Product (Product. php) products...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.