Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

clone versus no clone

Posted on 2013-12-07
10
Medium Priority
?
263 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
[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
  • 5
  • 5
10 Comments
 
LVL 111

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 111

Expert Comment

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

:-)

~Ray
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 111

Accepted Solution

by:
Ray Paseur earned 2000 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 111

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 111

Expert Comment

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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

This article discusses four methods for overlaying images in a container on a web page
This article discusses how to create an extensible mechanism for linked drop downs.
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.
Suggested Courses

610 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