Solved

clone vs reference in php

Posted on 2013-09-05
11
497 Views
Last Modified: 2013-09-30
how does
clone
differ from
reference
0
Comment
Question by:rgb192
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 3
  • +1
11 Comments
 
LVL 143

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 166 total points
ID: 39469497
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
 
LVL 57

Assisted Solution

by:Julian Hansen
Julian Hansen earned 167 total points
ID: 39469510
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
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 167 total points
ID: 39470259
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
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 

Author Comment

by:rgb192
ID: 39478969
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
 
LVL 143

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 166 total points
ID: 39479305
"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
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 39479324
Because '&'  &$anothervalue will continue to be modified except for when it is cloned?
Not sure I understand the question
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 167 total points
ID: 39479597
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
 

Author Comment

by:rgb192
ID: 39520145
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
 
LVL 57

Accepted Solution

by:
Julian Hansen earned 167 total points
ID: 39526883
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
 

Author Closing Comment

by:rgb192
ID: 39533082
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
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39533264
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

Featured Post

Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question