-
-
/** - * php shopping cart class
- * Singleton mode
- * Edit bbs.it-home.org
- */
- class Cart{
- static protected $ins; //Instance variable
- protected $item = array(); //Place items Container
//External calls are prohibited
- final protected function __construct(){
- }
//Cloning is prohibited
- final protected function __clone(){
- }
//Internal instantiation of the class
- static protected function Getins(){
- if(!(self::$ins instanceof self)){
- self::$ins = new self() ;
- }
return self::$ins;
- }
//In order to save the product across pages, put the object into the session
- public function Getcat(){
- if(!($_SESSION['cat']) || !($_SESSION['cat'] instanceof self)){
- $_SESSION['cat'] = self::Getins();
- }
return $_SESSION['cat'];
- }
//Check when enqueueing, whether it exists in $item.
- public function Initem($goods_id){
- if($this->Gettype() == 0){
- return false;
- }
- if(!(array_key_exists($goods_id,$this->item))){
- return false;
- }else{
- return $this->item[$goods_id]['num']; //Return the number of this product
- }
- }
//Add one Goods
- public function Additem($goods_id,$name,$num,$price){
- if($this->Initem($goods_id) != false){
- $this->item[$goods_id][' num'] += $num;
- return;
- }
$this->item[$goods_id] = array(); //A product is an array
- $this-> ;item[$goods_id]['num'] = $num; //Purchase quantity of this product
- $this->item[$goods_id]['name'] = $name; //Product name
- $this ->item[$goods_id]['price'] = $price; //unit price of the item
- }
//reduce one item
- public function Reduceitem($goods_id,$num){
- if($this->Initem($goods_id) == false){
- return;
- }
- if($num > $this->Getunm($goods_id)){
- unset($this-> item[$goods_id]);
- }else{
- $this->item[$goods_id]['num'] -=$num;
- }
- }
//Remove one Goods
- public function Delitem($goods_id){
- if($this->Initem($goods_id)){
- unset($this->item[$goods_id]);
- }
- }
-
//Return to the list of purchased items
- public function Itemlist(){
- return $this->item;
- }
//How many types of items are there in total?
- public function Gettype( ){
- return count($this->item);
- }
//Get the total number of a product
- public function Getunm($goods_id){
- return $this- >item[$goods_id]['num'];
- }
// Check how many items are in the shopping cart
- public function Getnumber(){
- $num = 0;
- if ($this->Gettype() == 0){
- return 0;
- }
foreach($this->item as $k=>$v){
- $ num += $v['num'];
- }
- return $num;
- }
//Calculate the total price
- public function Getprice(){
- $price = 0;
- if ($this->Gettype() == 0){
- return 0;
- }
foreach($this->item as $k=>$v){
- $ price += $v['num']*$v['num'];
- }
- return $price;
- }
//Clear the shopping cart
- public function Emptyitem(){
- $this->item = array();
- }
- }
- ?>
-
Copy code
Call example:
-
- include_once('Cart.php');
- $cart = Cart::Getcat();
- $cart->Additem('1','php learning tutorial (programmer Home Edition)','5','9999');
- print_r($cart);
- ?>
Copy code
|