【问题标题】:Fatal error: Uncaught Error: Call to undefined method stdClass::count()致命错误:未捕获的错误:调用未定义的方法 stdClass::count()
【发布时间】:2017-08-14 13:58:24
【问题描述】:

我在 products.php 页面中遇到了这个错误

致命错误:未捕获的错误:调用未定义的方法 C:\xampp\htdocs\shopCart\navigation.php:29 中的 stdClass::count() 堆栈 跟踪:#0 C:\xampp\htdocs\shopCart\layout_head.php(27):include() #1 C:\xampp\htdocs\shopCart\products.php(15): include('C:\xampp\htdocs...') #2 {main} 抛出 C:\xampp\htdocs\shopCart\navigation.php 在第 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)
  • 您的$cart_item 变量不是CartItem 类的对象。这是一个stdClassstdClass 类没有任何属性或方法。

标签: php fatal-error


【解决方案1】:

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

$cart_item = new CartItem($db);

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

【讨论】:

    猜你喜欢
    • 2019-07-19
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多