2017-08-14 158 views
-1

我得到这个错误在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]; 
     } 
} 

我该如何解决呢?

+0

如何运行一个不存在的函数?您创建了一个对象并立即尝试访问其中您从未定义过的函数?你想要做的是'$ cart_item = new CartItem($ db)'。 – Script47

+2

您的'$ cart_item'变量不是类“CartItem”的对象。它是一个'stdClass'。 'stdClass'类没有任何属性或方法。 – axiac

回答

1

您正在实例化$cart_item作为stdClass对象。我从你的代码示例和类假设它应该被实例化作为CartItem对象,像这样:

$cart_item = new CartItem($db); 

你都拿到了错误,因为stdClass没有一个count()方法。

+0

谢谢。它的工作:) – Foyez

相关问题