通过使用静态变量和单例模式,我认为创建一个简单的购物车会很容易,当加载另一个页面时,它会记住购物车中的哪些物品。
刷新页面时,我遇到了购物车不记得里面已经有什么的问题。
下面的代码是否有问题,或者我应该只使用全局变量还是 mysql 数据库。
存储状态的最佳方法是什么..
<?php
//create a singleton class
class shoppingCart {
private static $_shoppingCartItems = array();
private static $_instance = null;
private function __construct(){
}
public static function getInstance(){
if(self::$_instance == null)
self::$_instance = new shoppingCart();
return self::$_instance;
}
public function add(ShoppingItem $item){
$this->_shoppingCartItems[] = $item;
}
public function cartCount(){
return count($this->_shoppingCartItems);
}
}
?>
执行
$item = new shoppingItem();
$shoppingCart = shoppingCart::getInstance();
$shoppingCart->add($item);
$shoppingCart->add($item);
//should increment by 2 on each page load but it doesn't
echo $shoppingCart->cartCount();