?
Solved

clone versus no clone

Posted on 2013-12-07
10
Medium Priority
?
262 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
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 

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

WordPress Tutorial 1: Installation & Setup

WordPress is a very popular option for running your web site and can be used to get your content online quickly for the world to see. This guide will walk you through installing the WordPress server software and the initial setup process.

Question has a verified solution.

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

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…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

770 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