Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy of object identifier and reference to object identifier - which one should be used in real app?

Tags:

oop

php

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
like image 830
P K Avatar asked Jan 22 '12 15:01

P K


1 Answers

$instance2 has a copy of the identifier to the object test. So, it contains the same as $instance1. $instance3 contains a reference to $instance1. The difference would be the following:

$instance1 = new Test();
$instance2 = $instance1;
$instance3 = & $instance1;

var_dump($instance1 instanceof Test); // True
var_dump($instance2 instanceof Test); // True
var_dump($instance3 instanceof Test); // True

$instance3 = new AnotherTest();

var_dump($instance1 instanceof AnotherTest); // True
var_dump($instance2 instanceof AnotherTest); // False
var_dump($instance3 instanceof AnotherTest); // True

The same output would be returned if $instance1 was changed instead of $instance3.

But if we did the following:

$instance1 = new Test();
$instance2 = $instance1;
$instance3 = & $instance1;

$instance2 = new AnotherTest();

var_dump($instance1 instanceof AnotherTest); // False
var_dump($instance2 instanceof AnotherTest); // True
var_dump($instance3 instanceof AnotherTest); // False

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 $instance1 keeps is an identifier of the object, so:

$instance1 = new StdClass();
$instance2 = $instance1;

$instance1->my_property = 1;
var_dump($instance2->my_property); // Output: 1

Hope it's clearer now.

like image 174
Lumbendil Avatar answered Oct 31 '22 03:10

Lumbendil