2011-07-10 73 views
0

我正在研究将支持多种数据库方法的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 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 = new Mptt('mysqli');
$mptt->mysqli->addBranch(.....);

,但我不希望mysqli-> part ..所以我想如果我也许试图将$this->instance通过作为REFFERENCE然后$mptt将reffer到Mptt_MySQLi代替..

希望有人知道一个答案..

预先感谢 - 奥莱

+0

看看这个:http://components.symfony-project.org/dependency-injection/ – Mchl

回答

2

首先,new前不需&,如PHP 5的对象由默认引用传递。 你在做什么是正确的,但你不能在构造函数中做到这一点,你必须定义getInstance()方法,它将构造你的对象并返回引用到$this->instance

+1

此外,我想我可能会在这里使用更传统的驱动程序的解释。使“驱动程序”实例受保护,只能通过“Mptt”类工作。这样,您永远不需要知道您正在使用的驱动程序,因为“Mptt”将为其所有可用的驱动程序提供单个一致的接口。 – prodigitalson

+0

不知道我完全明白你的意思吗? –

+0

洛尔这是迟到..忘了我已经问过,现在登录,是的..接受这个答案:)迟到比从来没有更好我猜 –

相关问题