PHP从另一个类外部调用方法

时间:2011-02-03 17:28:10

标签: php oop

不确定OOP语法是否可以执行此操作... 我想要有一个调用mysqli对象的aclass

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类中的mysqli方法

4 个答案:

答案 0 :(得分:2)

您必须扩展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);
    }
}

答案 1 :(得分:0)

您可以定义__call方法:

public function __call($method, $arguments) {
    return call_user_func_array(array($this->dbh, $method), $arguments);
}
如果调用未定义或不可见的方法,则调用

__call

答案 2 :(得分:0)

你的代码是正确的。

您唯一要做的就是确保将Voovid_DB中的功能定义为公共功能。

无法从其他类访问

私有或受保护的方法

将您的mysqli对象存储在类中的公共字段中,然后您可以像这样访问它:

$dbconnect->mysqlField->query

答案 3 :(得分:0)

构造函数不应该返回任何内容。当您说$dbconnect = new Voovid_DB();时,您通常会尝试创建一个Voovid_DB对象,但看起来您正在使用它来尝试创建一个mysqli对象。在创建voovid_db对象后,不要将其作为构造函数并调用函数。

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