PHP从另一个类外部调用方法
不确定执行此操作的OOP语法。。。 我想要一个调用mysqli对象的类PHP从另一个类外部调用方法,php,oop,Php,Oop,不确定执行此操作的OOP语法。。。 我想要一个调用mysqli对象的类 class Voovid_DB { private $host = 'localhost'; private $user = 'blahblah'; private $password = 'blahblah'; private $name = 'blahblah'; public function __contstuct(){ $dbh= new mysqli( $
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方法。你要么扩展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
}
请注意,扩展了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);
}
}
您可以定义一个
\u调用
方法:
public function __call($method, $arguments) {
return call_user_func_array(array($this->dbh, $method), $arguments);
}
如果调用了未定义或不可见的方法,则会调用调用。您的代码是正确的
您必须做的唯一一件事是确保将Voovid_DB中的函数定义为public
无法从其他类访问私有或受保护的方法
将mysqli对象存储在类的公共字段中,然后可以按如下方式访问它:
$dbconnect->mysqlField->query
构造函数不应该返回任何内容。当你说
$dbconnect=new vovid_DB()代码>您通常会尝试创建一个vovid_DB对象,但看起来您正在使用它来尝试创建一个mysqli对象。不要将其设为构造函数,并在创建voovid_db对象后调用该函数
$obj = new voovid_DB();
$dbConnect = $obj->createMysqli();
你拼错了“构造”。你的程序中有拼写错误吗?如果是这样,您必须像调用任何其他函数一样调用它。