clone vs reference in php

how does
clone
differ from
reference
LVL 1
rgb192Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
clone copies the object.
reference is just a pointer to the same object.

in short:
$var = <some object>;
$othervar = $var;
$clonevar = clone $var;

if you now change something in $var,
=> it will also be changed in $othervar,
=> it will not NOT change in $clonevar , except if the "something" is actually a reference itself.
0
Julian HansenCommented:
Here is an example that explains the two
<?php // RAY_temp_rgb192.php
class myObject {
	public $somevalue;
	public $anothervalue;
	
	function __construct($somevalue, &$anothervalue)
	{
		$this->somevalue = $somevalue;
		$this->anothervalue = &$anothervalue;
	}
}

$x = array(1,2,3);
$y = array('apple','orange','pineapple');
$obj = new myObject($x, $y);
$x[] = 5;
$y[] = 'banana';

// The $y array is passed and assigned by reference 
// which means the anothervalue property does not make a copy
// of the $y array but points to it
// All changes to $y will reflect in anothervalue as they reference
// the same copy
echo '<pre>';
echo 'X: ' . PHP_EOL;
print_r($x);
echo 'Y: ' . PHP_EOL;
print_r($y);
echo 'Obj: ' . PHP_EOL;
print_r($obj);
echo '</pre>';

// When you clone an object you make a copy of all its properties i.e.
// A new object is created and its properties are intitialised to
// the values in the source object (unless you override the clone method)
// After cloning each object manages its own properties independently.
// In this case somevalue will vary from instance to instance as it 
// references its array by value so changes to it are to its own copy
// The anothervalue property is a reference so it also points to the
// same copy of the $y array as the original object and the $y
// variable
$newobj = clone $obj;
$x[] = 6;
$y[] = 'mango';
$newobj->somevalue[] = 12345;
$newobj->anothervalue[] = 'pawpaw';
echo '<pre>';
echo 'X: ' . PHP_EOL;
print_r($x);
echo 'Y: ' . PHP_EOL;
print_r($y);
echo 'Obj: ' . PHP_EOL;
print_r($obj);
echo 'NewObj: ' . PHP_EOL;
print_r($newobj);
echo '</pre>';
?>

Open in new window

As you can see if you run this - the reference variable ($y and $anothervalue) show the same array no matter where it is updated (i.e. $y[] = 'xxx' and $ob->anothervalue[] = 'yyy' both update the same instance of the array).
With a clone - property values are copied over to the new object. In this use of Clone it is the same as assignment i.e.

$yao = $newobj;

Will create a copy of $newobj and assign it to $yao.

The difference with clone - is that you can override the clone method and do some manipulating of the data in the new object as part of the copy.
0
Ray PaseurCommented:
Think of clone as being similar to new -- it creates an additional instance of the object, not just a pointer to the old object.  Clone is different from new in that instead of creating the original state of the object, it creates an exact copy at the time the instruction is executed, and the original object may have matured after instantiation.

<?php // RAY_temp_rgb192.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
echo '<pre>';


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28232255.html

// CREATE AN OBJECT
$obj = (object) 1;

// CREATE A REFERENCE TO THE OBJECT WITH THE ASSIGNMENT OPERATOR
$new = $obj;

// ADD TO THE OBJECT VIA THE 'new' POINTER
$new->scalar++;

// SHOW THAT THIS MODIFIED THE ORIGINAL OBJECT
var_dump($obj);

// CLONE THE OBJECT AND ADD TO THE CLONE
$xyz = clone $new;
$xyz->scalar++;

// SHOW THAT THESE ARE DIFFERENT OBJECTS
var_dump($obj);
var_dump($xyz);

Open in new window

See http://php.net/manual/en/language.oop5.cloning.php

In the Singleton design pattern you might make the __clone() method final and private to avoid accidental proliferation.
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

rgb192Author Commented:
Julian:
Because '&'  &$anothervalue will continue to be modified except for when it is cloned?

Ray:
In the Singleton design pattern you might make the __clone() method final and private to avoid accidental proliferation.

explain please

AngelIII:
=> it will not NOT change in $clonevar , except if the "something" is actually a reference itself.
how could an example of this happen?
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
"something" means a property which points to another object ...
proper cloning might be to clone also that referenced object, OR to keep it as a reference.
 this depends on the case ...
0
Julian HansenCommented:
Because '&'  &$anothervalue will continue to be modified except for when it is cloned?
Not sure I understand the question
0
Ray PaseurCommented:
In the Singleton design pattern you might make the __clone() method final and private to avoid accidental proliferation.
I don't think I can create a better explanation than the original documentation.

To make a new object instance from a class you use the keyword new and you get the original object.  You might change properties in that object in the course of your programming.  If you wanted to get a copy of the changed object, you would use clone.  In the case of a database singleton, you would not want a programmer to clone the connection object.  Cloning can go beyond merely copying the object; it can specify programmatic rules for creating the copied object.
http://php.net/manual/en/language.types.object.php
http://php.net/manual/en/language.oop5.visibility.php
http://php.net/manual/en/language.oop5.cloning.php
http://php.net/manual/en/language.oop5.final.php
0
rgb192Author Commented:
Because '&'  &$anothervalue will continue to be modified except for when it is cloned?

Not sure I understand the question


will  &$anothervalue will continue to be modified


will  clone &$anothervalue will continue to be modified
0
Julian HansenCommented:
When an object is cloned - the anothervalue variable is copied so the clone has its own copy.

Any change made to the value in the clone will now be independent of that made to the variable in the object that WAS cloned.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rgb192Author Commented:
When an object is cloned - the anothervalue variable is copied so the clone has its own copy.

Any change made to the value in the clone will now be independent of that made to the variable in the object that WAS cloned.

clone copies the object.
reference is just a pointer to the same object.



Thanks
0
Ray PaseurCommented:
After seeing this question, I wrote an article to explain and demonstrate the difference:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html

Thanks for the points, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.