致命错误:未捕获错误:调用未定义的方法stdClass :: count()

时间:2017-08-14 13:58:25

标签: php fatal-error

我在products.php页面

中遇到此错误
  

致命错误:未捕获错误:调用未定义的方法   C:\ xampp \ htdocs \ shopCart \ navigation.php中的stdClass :: count():29堆栈   跟踪:#0 C:\ xampp \ htdocs \ shopCart \ layout_head.php(27):include()#1   C:\ XAMPP \ htdocs中\询\ products.php(15):   include(' C:\ xampp \ htdocs ...')#2 {main}引入   第29行的C:\ xampp \ htdocs \ shopCart \ navigation.php

这是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类中的count函数

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];
        }
}

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您正在将$cart_item实例化为stdClass对象。我假设您的代码示例和类应该将其实例化为CartItem对象,如下所示:

$cart_item = new CartItem($db);

您收到错误是因为stdClass没有count()方法。