我正在定义共享公共数据库的模型。但是,我在通过require_once()
传递PDO对象时遇到问题。我收到以下错误:
Fatal error: Call to a member function prepare() on a non-object...
我猜这只是一个范围问题。我尝试在两个文件中将$database
声明为global
,但这似乎不起作用。有什么想法吗?
的common.php
$host = 'localhost';
$dbname = 'database';
$username = 'user';
$password = 'pass';
$database = new PDO("mysql:host=$host;dbname=$dbname", $username, $password, array(PDO::ATTR_PERSISTENT => true));
product.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);
}
}
答案 0 :(得分: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);
答案 1 :(得分: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);