2011-02-03 113 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();