In this following article I have demonstrated how to create class and its objects.
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
clone objects