0

I'm working on a MPTT object that will support several database methods. First of is MySQL and MySQLi. Now I've created it like this

Mptt - The main object that will load the correct sub 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..

Hopefully someone knows an answer to this..

Thanks in advance - Ole

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Ole Aass
  • 173
  • 1
  • 4

1 Answers1

2

First, no need of & before new, as in PHP 5 objects are passed by reference by default. 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.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • 1
    Also, i think i might use a more traditional interpretation of a driver here. Make the "driver" instance protected and only work through the `Mptt` class. This way you never need to know what driver you are working with as `Mptt` will provide a single consistent interface to all of its available drivers. – prodigitalson Jul 10 '11 at 15:06
  • Not sure i fully understood what you mean about this? – Ole Aass Jul 10 '11 at 15:15
  • Lol this was late.. Forgot I had asked and logged in now, and yeah.. Accepted this as the answer :) better late than never i guess – Ole Aass Jan 13 '13 at 11:59