This is related to question: How does the "&" operator work in a PHP function?
Is there simple code to show the difference between
passing the object as reference
vs
passing the object's reference as value?
This is related to question: How does the "&" operator work in a PHP function?
Is there simple code to show the difference between
passing the object as reference
vs
passing the object's reference as value?
<?php
class X {
var $abc = 10;
}
class Y {
var $abc = 20;
function changeValue(&$obj){//1>here the object,$x is a reference to the object,$obj.hence it is "passing the object's reference as value"
echo 'inside function :'.$obj->abc.'<br />';//2>it prints 10,bcz it accesses the $abc property of class X, since $x is a reference to $obj.
$obj = new Y();//but here a new instance of class Y is created.hence $obj became the object of class Y.
echo 'inside function :'.$obj->abc.'<br />';//3>hence here it accesses the $abc property of class Y.
}
}
$x = new X();
$y = new Y();
$y->changeValue($x);//here the object,$x is passed as value.hence it is "passing the object as value"
echo $x->abc; //4>As the value has been changed through it's reference ,hence it calls $abc property of class Y not class X.though $x is the object of class X
?>
o/p :
inside function :10
inside function :20
20