Avatar of rgb192
rgb192
Flag for United States of America asked on

clone versus no clone

<?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
PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
Ray Paseur

Have a read of this article:
https://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

rgb192

ASKER
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?
Ray Paseur

Why did a boss tell you to make a snapshot?   I dunno.  Ask the boss!

:-)

~Ray
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
rgb192

ASKER
I meant to ask. Why would you use clone? In what type of project is clone used?
ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
rgb192

ASKER
Does arr[] hold 3 objects. Would $arr[1] be ray
Ray Paseur

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!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
rgb192

ASKER
$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
rgb192

ASKER
thanks.
Ray Paseur

Thanks for the points!
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck