我得到這個錯誤在products.php頁致命錯誤:未捕獲的錯誤:調用未定義的方法stdClass的::計數()
Fatal error: Uncaught Error: Call to undefined method stdClass::count() in C:\xampp\htdocs\shopCart\navigation.php:29 Stack trace: #0 C:\xampp\htdocs\shopCart\layout_head.php(27): include() #1 C:\xampp\htdocs\shopCart\products.php(15): include('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\shopCart\navigation.php on line 29
這是navigation.php頁的錯誤部分。最後一行是29
// count products in cart
$cart_item = new \stdClass();
$cart_item->user_id=1; // default to user with ID "1" for now
$cart_count=$cart_item->count();
在cartItem類這是計數功能
class CartItem{
// database connection and table name
private $conn;
private $table_name = "cart_items";
// object properties
public $id;
public $product_id;
public $quantity;
public $user_id;
public $created;
public $modified;
// constructor
public function __construct($db){
$this->conn = $db;
}
// count user's items in the cart
public function count() {
// query to count existing cart item
$query = "SELECT count(*) FROM " . $this->table_name . " WHERE user_id=:user_id";
// prepare query statement
$stmt = $this->conn->prepare($query);
// sanitize
$this->user_id=htmlspecialchars(strip_tags($this->user_id));
// bind category id variable
$stmt->bindParam(":user_id", $this->user_id);
// execute query
$stmt->execute();
// get row value
$rows = $stmt->fetch(PDO::FETCH_NUM);
// return
return $rows[0];
}
}
我該如何解決呢?
如何運行一個不存在的函數?您創建了一個對象並立即嘗試訪問其中您從未定義過的函數?你想要做的是'$ cart_item = new CartItem($ db)'。 – Script47
您的'$ cart_item'變量不是類「CartItem」的對象。它是一個'stdClass'。 'stdClass'類沒有任何屬性或方法。 – axiac