简体   繁体   中英

Return a reference of an object instance

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM