Passing PHP Objects 'by value' and 'by reference'
Although PHP 5 by default passes objects by ref these are 'readonly' refs and not 'readwrite' refs !code
class o{
var $x=1;
var $y=2;
}
function f($o) {
$o->x=3;
$o->y=4;
$o = new o; // no effect on passed object
}
function g(&$o) { // the danger of using & !
$o->x=5;
$o->y=6;
$o = new o; // destroy/overwrite passed object
}
$o = new o;
var_dump($o);
f($o);
var_dump($o);
g($o);
var_dump($o);
var $x=1;
var $y=2;
}
function f($o) {
$o->x=3;
$o->y=4;
$o = new o; // no effect on passed object
}
function g(&$o) { // the danger of using & !
$o->x=5;
$o->y=6;
$o = new o; // destroy/overwrite passed object
}
$o = new o;
var_dump($o);
f($o);
var_dump($o);
g($o);
var_dump($o);
output
$ php p.php
object(o)#1 (2) {
["x"]=>
int(1)
["y"]=>
int(2)
}
object(o)#1 (2) {
["x"]=>
int(3)
["y"]=>
int(4)
}
object(o)#2 (2) {
["x"]=>
int(1)
["y"]=>
int(2)
}REFERRERS
PHP