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?
cl开发者_如何学Pythonass 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();
}
}
If you are using PHP5+, in almost all cases, objects are passed by reference by default.
As objects are already passed "by reference" in PHP5+ then using &
you would actually pass a "reference to a reference to an object" not just a simple "reference to an object". This can be critical because it will allow the function within its local scope to change the actual reference globally and potentially remove the object entirely. For example one would think that the following example of passing the object by ref and passing by "normally" is completely the same:
$aa = new stdclass;
$aa->aa = 1;
byRef($aa);
function byRef(&$aaa) {
$aaa->aa = 2;
}
var_dump($aa); // Outputs {aa:2}
$bb = new stdclass;
$bb->bb = 1;
byVal($bb);
function byVal($bba) {
$bba->bb = 2;
}
var_dump($bb); // Outputs {bb:2}
Judging by the output it looks the same. But is it a good practice? Depends what you wanted to do. Look at the same example where we destroyed the original reference and "deleted" the object:
$aa = new stdclass;
$aa->aa = 1;
byRef($aa);
function byRef(&$aaa) {
$aaa->aa = 2;
$aaa = 0; // We are changing $aa, not $aaa, because $aaa is just a reference
}
var_dump($aa); // Outputs int:0, $aa is not an object anymore
$bb = new stdclass;
$bb->bb = 1;
byVal($bb);
function byVal($bba) {
$bba->bb = 2;
$bba = 0;
}
var_dump($bb); // Outputs {bb:0}
The code speaks for itself. In some cases this is needed, in other this is critical. In my opinion unless you really know what are you doing do not pass by reference.
精彩评论