我正在尝试将商品添加到购物车。
我收到以下错误Fatal Error Call to a member function AddItem() on a non-object
这是我的购物车类
class shoppingCart
{
protected $items = array();
public function AddItem($product_id)
{
if (array_key_exists($product_id, $this->items))
$this->items[$product_id] = $this->items[$product_id] + 1;
else
$this->items[$product_id] = 1;
}
public function GetItems()
{
return array_keys($this->items);
}
public function GetItemQuantity($product_id)
{
return $this->items[$product_id];
}
}
导致错误的特定行是$shopping_cart->AddItem($product_id);
这是完整的部分:
$product_id = $_REQUEST['id'];
if (product_exists($product_id))
{
$shopping_cart->AddItem($product_id);
echo "Item Added";
}
有趣的是,我在函数文件中添加 session_start() 后就开始收到此错误,如下所示:
session_start();
// Getting the Catalogue
function get_xml_catalog()
{
return new SimpleXMLElement(file_get_contents(STORE_XML_FILE));
}
// Creating the product list on courses.php
function generate_items()
{
foreach (get_xml_catalog() as $product)
{
echo '<div class="span4">
<div class="service-main">
<div class="service-icon"> <i class="icon-beaker"></i> </div>
<div class="service-info">
<h3>',$product->title,'</h3>
<p>',$product->description,'</p>
<a href="addToCart.php?id=',$product->id,'">Add To Cart</a>
</div>
</div>
</div>
';
}
}
//Passing Data into the shopping cart session.
function get_shopping_cart()
{
if (!isset($_SESSION['cart']))
return new ShoppingCart();
else
return unserialize($_SESSION['cart']);
}
function set_shopping_cart($cart)
{
$_SESSION['cart'] = serialize($cart);
}
//Checking to make sure the product ID is valid (exists) in our catalogue.
function product_exists($product_id)
{
foreach (get_xml_catalog() as $product)
{
if ($product->id==$product_id)
return true;
}
return false;
}
我在网上读到添加序列化/反序列化可以修复这个错误,但这并没有改变任何东西。我不确定我做错了什么 - 当我删除session_start()
功能工作时,我可以 var_dump $shopping_cart 让项目通过它。当我有 session_start() 时,shoppingCart 中的所有功能都不起作用。即使我更改AddItem()
为不存在的功能,我仍然会收到相同的错误。我确定这与会话有关。