[英]Return a reference of an object instance
I'm working on a MPTT object that will support several database methods.我正在研究支持多种数据库方法的 MPTT object。 First of is MySQL and MySQLi.
首先是 MySQL 和 MySQLi。 Now I've created it like this
现在我已经这样创建了
Mptt - The main object that will load the correct sub object Mptt - 将加载正确子 object 的主 object
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;
}
}
}
now, the only way i've been successfull in getting this working is to do something like现在,我成功完成这项工作的唯一方法就是做类似的事情
add public variables for each driver and do it like this为每个驱动程序添加公共变量并这样做
$mptt = new Mptt('mysqli');
$mptt->mysqli->addBranch(.....);
but i don't want that mysqli-> part
.. So i thought if i maybe tried to pass the $this->instance
as a refference then $mptt
would reffer to Mptt_MySQLi
instead..但我不想要那个
mysqli-> part
.. 所以我想如果我可能试图将$this->instance
作为引用传递,那么$mptt
会Mptt_MySQLi
..
Hopefully someone knows an answer to this..希望有人知道这个问题的答案..
Thanks in advance - Ole在此先感谢-Ole
First, no need of &
before new
, as in PHP 5 objects are passed by reference by default.首先,在
new
之前不需要&
,如在 PHP 中,默认情况下通过引用传递 5 个对象。 What you are doing is correct, but you can't do this in the constructor, you have to define getInstance()
method, which will construct your object and return the reference to $this->instance
.您所做的是正确的,但是您不能在构造函数中执行此操作,您必须定义
getInstance()
方法,该方法将构造您的 object 并返回对$this->instance
的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.