Solved

clone versus no clone

Posted on 2013-12-07
10
253 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 108

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 108

Expert Comment

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

:-)

~Ray
0
 

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 108

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

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

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 108

Expert Comment

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

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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 …

758 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now