Php 返回对象实例的引用
我正在研究一个MPTT对象,它将支持多种数据库方法。首先是MySQL和MySQLi。现在我就这样创造了它 Mptt—将加载正确子对象的主对象Php 返回对象实例的引用,php,object,instance,mptt,Php,Object,Instance,Mptt,我正在研究一个MPTT对象,它将支持多种数据库方法。首先是MySQL和MySQLi。现在我就这样创造了它 Mptt—将加载正确子对象的主对象 class Mptt { /** * Array of available driver types * @var array */ private $availableDrivers = array('mysqli','mysql'); /** * Holding an instance of the mptt object correspon
class Mptt {
/**
* Array of available driver types
* @var array
*/
private $availableDrivers = array('mysqli','mysql');
/**
* Holding an instance of the mptt object corresponding to the selected driver
* @var object
*/
public $instance;
public function __construct($driver = 'mysqli', $autoConnect = false, $info = array()) {
if (in_array($driver, $this->availableDrivers)) {
switch ($driver) {
case 'mysqli':
$this->instance =& new Mptt_MySQLi();
break;
case 'mysql':
$this->instance =& new Mptt_MySQL();
break;
}
return $this->instance;
}
}
}
现在,我成功地让它工作的唯一方法就是
为每个驱动程序添加公共变量,如下所示
$mptt=newmptt('mysqli')代码>
$mptt->mysqli->addBranch(…)代码>
但是我不想要那种mysqli->part
。。因此,我想如果我尝试将$this->instance
作为refreference传递,那么$mptt
将改为mptt\u MySQLi
希望有人知道答案
提前谢谢
-Ole首先,在新建之前不需要和,因为在PHP5中,默认情况下对象是通过引用传递的。
您所做的是正确的,但是您不能在构造函数中这样做,您必须定义getInstance()
方法,该方法将构造您的对象并返回对$this->instance
的引用。请检查:另外,我想我可能在这里使用更传统的驱动程序解释。使“驱动程序”实例受保护,并且只在Mptt
类中工作。这样你就不需要知道你使用的是什么驱动程序,因为Mptt
将为所有可用的驱动程序提供一个统一的接口。我不确定我是否完全理解你的意思?哈哈,这太晚了。。忘了我已经问过了,现在已经登录了,是的。。我接受了这个答案:)我想迟做总比不做好