Solved

clone versus no clone

Posted on 2013-12-07
10
255 Views
Last Modified: 2013-12-13
<?php
class CopyClass{
  public $name;
}

$first= new CopyClass();
$first->name="Number 1";
$second= clone $first;
echo "first = ".$first->name."<br>";
$second->name="Number 2";
echo "first = " . $first->name . "<br>";
echo "second = " . $second->name . "<br>";

Open in new window


I know that when the word 'clone' is used
Changing second, does not change first

But is there a real world example of clone versus no clone
0
Comment
Question by:rgb192
  • 5
  • 5
10 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39703437
Have a read of this article:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html

The real-world example might exist in an environment where an object gets mutated and you need a second copy of the object.  Perhaps you call a method after property  #1 is added to the object, then another method after property #2, etc.  If you want a record of the state of the object after each property is added you can clone the object after each addition.

You can also nullify the clone() method, as in a Singleton design pattern.

<?php // RAY_database_singleton.php
error_reporting(E_ALL);


// SINGLETON DATA BASE CONNECTION CLASS
class Database
{
    // CLASS PROPERTIES ARE ALL PRIVATE
    private static $connection;
    private static $instance;

    // CONNECTION VALUES
    const DB_HOST = 'localhost';
    const DB_USER = '?';
    const DB_PASS = '?';
    const DB_NAME = '?';

    // NULLIFY THE CLONE
    final private function __clone() {}

    // OUR ONLY PUBLIC METHOD RETURNS THE CONNECTION
    public static function getConnection()
    {
        if (!self::$instance) self::$instance = new self();
        return self::$connection;
    }

    // CONSTRUCTOR CREATES THE CONNECTION
    private function __construct()
    {
        self::$connection
        = new mysqli
        ( self::DB_HOST
        , self::DB_USER
        , self::DB_PASS
        , self::DB_NAME
        )
        ;
        if (self::$connection->connect_error)
        {
            trigger_error(self::$connection->connect_error, E_USER_ERROR);
        }
    }
}

$mysql1 = database::getConnection();
$mysql2 = database::getConnection();


// PROVE THAT THESE ARE THE SAME OBJECT http://php.net/manual/en/language.oop5.object-comparison.php
if ($mysql1 === $mysql2) echo 'EQUAL';

// SHOW THE OBJECT
var_dump($mysql1);

Open in new window

0
 

Author Comment

by:rgb192
ID: 39705095
Running in a debugger
name--------------- value------------------ type
$mysql1-----------none(empty)----------object(myqli)

and this was output
EQUALobject(mysqli)#2 (0) { }


If you want a record of the state of the object after each property is added you can clone the object after each addition.


Okay I understand clone alittle better when you have example (if coder needs a snapshot) so maybe real world is windows os system restore

Or maybe a boss/client told you to make a snapshot, if so why?
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39707453
Why did a boss tell you to make a snapshot?   I dunno.  Ask the boss!

:-)

~Ray
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:rgb192
ID: 39707596
I meant to ask. Why would you use clone? In what type of project is clone used?
0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39708912
Here is an example.  I needed an array of similar but distinct "mock objects" for test data.  In real life, these objects would probably come from rows of a query results set.  Because objects are passed by reference, each mutation of $object would change the original object.  By using clone, I am able to get distinct objects with different properties.

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

// SORT AN ARRAY OF OBJECTS BY LASTNAME, FIRSTNAME
// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28312470.html#a39708223

// SETUP SOME TEST DATA
$object = new stdClass;

$object->id    = "1";
$object->fname = "Ray";
$object->lname = "Paseur";
$object->work  = "Programmer";
$object->func  = "testData";
$arr[] = clone $object;

$object->id    = "2";
$object->fname = "John";
$object->lname = "James";
$object->work  = "Student";
$arr[] = clone $object;

$object->id    = "3";
$object->fname = "Dave";
$object->lname = "Baldwin";
$object->work  = "Expert";
$arr[] = clone $object;

// A FUNCTION TO COMPARE BY NAMES
function cmp_name($a, $b)
{
    $a_name = $a->lname . $a->fname;
    $b_name = $b->lname . $b->fname;
    if ($a_name == $b_name) return 0;
    return ($a_name < $b_name) ? -1 : 1;
}

// SORT THE ARRAY
usort($arr, 'cmp_name');

// SHOW THE WORK PRODUCT
print_r($arr);

Open in new window

0
 

Author Comment

by:rgb192
ID: 39712457
Does arr[] hold 3 objects. Would $arr[1] be ray
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39712711
Arrays are numbered starting at zero.  Numeric array keys are frequently subject to being reset.  The array keys are shown in the print_r() output.  Just install the script and run it to see what it does with the data.  Easy!
0
 

Author Comment

by:rgb192
ID: 39718011
$object->id    = "1";
$object->fname = "Ray";
$object->lname = "Paseur";
$object->work  = "Programmer";
$object->func  = "testData";
$arr[] = /*clone*/ $object;

$object->id    = "2";
$object->fname = "John";
$object->lname = "James";
$object->work  = "Student";
$arr[] = /*clone*/ $object;

$object->id    = "3";
$object->fname = "Dave";
$object->lname = "Baldwin";
$object->work  = "Expert";
$arr[] = /*clone*/ $object;

Open in new window


only had the last object repeated 3 times
so now I understand clone better
0
 

Author Closing Comment

by:rgb192
ID: 39718014
thanks.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39718025
Thanks for the points!
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

777 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