2012-11-27 65 views
0

我正在定義共享公用數據庫的模型。但是,我無法通過require_once()傳遞PDO對象。我收到以下錯誤:PHP變量作用域:將外部對象傳遞給一個類

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

我猜這只是一個範圍問題。我試圖在兩個文件中聲明$databaseglobal,但似乎沒有奏效。有任何想法嗎?

的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); 
    } 

} 
+1

'$ database'被定義在類外;和正常的函數類似,你不能在類中看到變量。或者像MrCode所建議的那樣將其傳遞給班級,或者像Rawkode所建議的那樣將其設置爲全局(不推薦)。 – Peon

回答

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); 
+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);