Search code examples
phpobjectpass-by-referencepass-by-value

Pass object by reference or value


I'm sure this question has been asked a thousand times, but i had trouble finding an answer i could understand or use anywhere.

In my project, i need to use my sql class and other misc classes, in alot of the classes. Then i'm qurious to know what's the best way performance wise to pass the objects.

Should i pass the objects to the classes construct as reference?

class MyClass {
    private $_link;

    function __construct(&$db) {
        $this->_link =& $db;
    }
}

or value..

class MyClass {
    private $_link;

    function __construct($db) {
        $this->_link = $db;
    }
}

or simply create a new object?

class MyClass {
    private $_link;

    function __construct() {
        $this->_link = new DB();
    }
}

Solution

  • If you are using PHP5+, in almost all cases, objects are passed by reference by default.