2011-02-03 114 views
1

不知道OOP的語法來做到這一點以外的調用方法... 我想有ACLASS調用的mysqli對象PHP從另一個類

class Voovid_DB { 
    private $host = 'localhost'; 
    private $user = 'blahblah'; 
    private $password = 'blahblah'; 
    private $name = 'blahblah'; 

    public function __contstuct(){ 
     $dbh= new mysqli($this->host, $this->user, $this->password, $this->name); 
     return $dbh; 
    } 

    //get and set methods for host, user etc... go here  
} 

現在我想訪問所有在mysqli的方法,像這樣

$dbconnect = new Voovid_DB(); 
if ($result = $dbconnect->query("SELECT first_name, last_name FROM members WHERE member_id=9")) { 
    while ($row = $result->fetch_assoc()) { 
     $first_name = ucfirst($row['first_name']); 
     $last_name = ucfirst($row['last_name']); 
    } 
} else { 
    $errors = $dbconnect->error; 
} 

我是新來的PHP OOP,不知道怎麼去給Voovid_DB類

+2

你拼錯 「__construct」。你的程序拼寫錯了嗎?如果是這樣,你必須像任何其他功能一樣調用它。 – 2011-02-03 17:40:24

回答

2

你必須要麼擴展庫MySQLi類中的mysqli的方法,或圍繞它建立一個代理。

最簡單的可能是把它擴大:

class Voovid_DB extends MySQLi { 
    private $host = 'localhost'; 
    private $user = 'blahblah'; 
    private $password = 'blahblah'; 
    private $name = 'blahblah'; 

    public function __construct(){ 
     // call parent (MySQLi) constructor 
     parent::__construct($this->host, $this->user, $this->password, $this->name); 
    } 

    // no need for other methods, they already are there 
} 

通知的extends MySQLi

然後你的第二個代碼snipet應該工作。

或者,建立一個代理:

class Voovid_DB { 
    private $host = 'localhost'; 
    private $user = 'blahblah'; 
    private $password = 'blahblah'; 
    private $name = 'blahblah'; 
    private $dbh; 

    public function __construct(){ 
     $this->dbh = new MySQLi($this->host, $this->user, $this->password, $this->name); 
    } 

    // this will proxy any calls to this class to MySQLi 
    public function __call($name, $args) { 
     return call_user_func_array(array($this->dbh,$name), $args); 
    } 
} 
0

你可以定義一個__call方法:

public function __call($method, $arguments) { 
    return call_user_func_array(array($this->dbh, $method), $arguments); 
} 

__call是,如果未定義或inivisible方法被稱爲調用。

0

你的代碼是正確的。

你唯一需要做的就是確保你在Voovid_DB中將你的函數定義爲公共的。

私人或受保護的方法不能從其他類訪問

儲存在你的類中的公共領域的mysqli的對象,那麼你可以像這樣訪問:

$dbconnect->mysqlField->query 
0

構造函數不應該回報什麼。當你說$dbconnect = new Voovid_DB();時,你通常會嘗試創建一個Voovid_DB對象,但它看起來像你正在使用它來嘗試創建一個mysqli對象。在創建voovid_db對象後,不要將其設置爲構造函數並調用該函數。

$obj = new voovid_DB(); 
$dbConnect = $obj->createMysqli();