PHP Simple Shopping Cart class design _php Tutorial

Source: Internet
Author: User
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 ...

  • Related Article

    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.