我正在尝试将商品添加到购物车。session_start()导致致命错误调用一个非对象的成员函数AddItem()?
我收到以下错误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()
更改为不存在的函数时,我仍然会得到相同的错误。我确定这是一些与会话有关的问题。
在发生错误的行输出之前,var_dump($ shopping_cart)是什么? – TheWolf
它出现为空。不知道为什么,因为$ shopping_cart应该有新的shoppingCart()传递给它,或者只是返回$ _SESSION ['cart'] – Fahad
我想你必须事先调用'$ shopping_cart = get_shopping_cart();'。 – TheWolf