0

我正在定义共享公共数据库的模型。但是,我无法通过require_once(). 我收到以下错误:

Fatal error: Call to a member function prepare() on a non-object...

我猜这只是一个范围问题。我尝试在两个文件中都声明$database为 a global,但这似乎不起作用。有任何想法吗?

常见的.php

$host = 'localhost';
$dbname = 'database';
$username = 'user';
$password = 'pass';

$database = new PDO("mysql:host=$host;dbname=$dbname", $username, $password, array(PDO::ATTR_PERSISTENT => true));

产品.php

require_once('common.php');

class Product {

  function fetch_from_category($category) {
    $query = $database->prepare('SELECT * FROM product WHERE product.category = ?');
    $query->execute($category);
    return $query->fetchAll(PDO::FETCH_ASSOC);
  }

}
4

2 回答 2

1

传递$database给类,然后将其存储为属性并使用$this->database

class Product {

  protected $database;

  public function setDb($db)
  {
      $this->database = $db;
  }

  function fetch_from_category($category) {
    $query = $this->database->prepare('SELECT * FROM product WHERE product.category = ?');
    $query->execute($category);
    return $query->fetchAll(PDO::FETCH_ASSOC);
  }

}

$p = new Product();
$p->setDb($database);
于 2012-11-27T12:41:29.437 回答
1

确实是范围问题,$database里面没有定义Product::fetch_from_category。您应该在实例化它时将其传递给对象:

class Product {

  protected $database;

  public function __construct(PDO $database) {
      $this->database = $database;
  }

  public function fetch_from_category($category) {
      $query = $this->database->prepare('SELECT * FROM product WHERE product.category = ?');
      $query->execute($category);
      return $query->fetchAll(PDO::FETCH_ASSOC);
  }

}

...

require_once 'common.php';
require_once 'product.php';

$product = new Product($database);
于 2012-11-27T12:42:03.853 回答