In the below example, any operation done by $instance2 and $instance3 modifies original object.
My question is:
If a copy of an original object identifier and a reference to the original object identifier does same job, which one should be used in real applications?
What are the pros and cons of using a copy of object identifier and of using a reference to the object identifier?
I read the PHP manual but am unable to differentiate in terms of usage because both do the same job.
$instance1 = new test(1);
$instance2 = $instance1;
$instance3 =& $instance1;
//$instance1 -> original object identifier of the new object.
//$instance2 -> copy of object identifier $instance1
//$instance3 -> reference to the object identifier $instance1
$instance2has a copy of the identifier to the object test. So, it contains the same as$instance1.$instance3contains a reference to$instance1. The difference would be the following:The same output would be returned if
$instance1was changed instead of$instance3.But if we did the following:
So:
Modification of a variable which has been passed by reference or assigned by reference (using the
&operand) or of the variable to which it references, modifies both, while modification of a copied variable modifies only the given variable.Still, you must remember that what
$instance1keeps is an identifier of the object, so:Hope it’s clearer now.