YogeshChauhan . com

How to Clone Objects in PHP?

in Misc on February 13, 2020

In this following article I have demonstrated how to create class and its objects.

OOP, Class and Objects Strategies For Beginners (PHP)

Now, once you know how to create objects, you'd want to create copies of those objects to cut down the lines of code you write and for simplicity purposes as well. But, making object assignments does not copy objects in their entirety.

Let's define a simple User class without any methods. Let's give that User class a property name $name.


class User{
  public $name;
}

Now, lets create one object of the User class and give that object a name by using $name property.


//code inside PHP

$user1 = new User();
$user1->name = "Bob";

Now, let's create one more object using object 1 and assign a different name to that object.


//code inside PHP

$user2 = $user1;
$user2->name = "Jon";

So, the code file contains:


//code inside PHP

$user1 = new User();
$user1->name = "Bob";
 
$user2 = $user1;
$user2->name = "Jon";

echo "user 1 name is : " .$user1->name . "<br>";
echo "user 2 name is : " .$user2->name;

class User{
  public $name;
}

Let's take a look at the output:


//output

user 1 name is : Jon
user 2 name is : Jon

A bit strange result.

The reason why we are getting same names in the output is because both of the objects refer to the same object. So, when we change the name for object 2 after creating a copy of object 1, it will change the name for object 1 as well.

To avoid this kind of failure, we can use clone operator that creates a new instance of a class and copies all those properties and values from original instance to the new one.

Let's take a look at the same example with clone.


//code inside PHP

$user1 = new User();
$user1->name = "Bob";
  
$user2 = clone $user1;
$user2->name = "Jon";
  
echo "user 1 name = " . $user1->name . "<br>";
echo "user 2 name = " . $user2->name;
  
class User {
  public $name;
}

//output

user 1 name = Bob
user 2 name = Jon
amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Attributes and Properties in JavaScript and HTMLHTMLHow to change CSS with jQuery?CSSCheck if mixin is being called in a style rule or not in SCSSSCSSAlternate Style Sheets in CSSCSSHow to switch dark and light themes using pure CSS?CSSOrder By and Group By in PostgresPostgres