Object cloning of PHP object oriented programming clone and magic method __clone of usage analysis

  • 2021-12-12 03:52:58
  • OfStack

This paper illustrates the use of object cloning clone and magic method __clone () in PHP object-oriented programming. Share it for your reference, as follows:

1. Object cloning clone

A major disadvantage of PHP4 object-oriented functionality is that it treats objects as another data type, which makes many common OOP methods unusable, such as design patterns. These methods rely on passing objects as references to other class methods rather than as values, which is the default for PHP. Fortunately, PHP 5 solves this problem, and all objects are now treated as references by default. However, since all objects are treated as references rather than values, it is now more difficult to copy objects. If you try to copy a referenced object, this will only point to the address location of the original object. In order to solve the replication problem, PHP provides a clone clone (Keyword, not method) is an explicit method of an object.

You can prefix the object with clone Keyword to clone an object, as follows:


destinationObject = clone targetObject;

Clone object:


<?php
class Person{
  var $name;
  var $sex;
  var $age;
  function __construct($name, $sex, $age){
    $this->name = $name;
    $this->sex = $sex;
    $this->age = $age;
  }
  function say(){
    echo " My name: " . $this->name . " , gender: " . $this->sex . " , age: " .$this->age . "<br />";
  }
}
$person1 = new Person(" Zhang 33", " Male ", 23);
$person2 = clone $person1;  // Use clone Keyword cloning / Copy objects, create 1 Copies of objects 
$person3 = $person1;  // This is not copying objects, but copying more than one object 1 Access a reference to the object 
$person1->say();  // Call the speech mode in the original object and print all the attribute values in the original object 
$person2->say();  // Call the speaking mode in the copy object and print all the property values in the clone object 
$person3->say();  // Call the speech mode in the original object and print all the attribute values in the original object 
?>

2. Magic method __clone ()

In the above program, 1 created two objects, of which 1 object was created through clone A cloned copy of the keyword. Two objects can be completely independent, but the values of their members and attributes are exactly the same. If you need to re-assign initial values to the member attributes of the cloned copy object when cloning, you can declare a magic method "__clone ()" in the class. This method is called automatically when the object is cloned, so the cloned copy can be reinitialized by this method. __clone() Method does not require any parameters. Rewrite the code in the above example by 1 to add magic methods to the class __clone() That reinitializes the member properties in the replica object.


<?php
class Person{
  var $name;
  var $sex;
  var $age;
  function __construct($name, $sex, $age){
    $this->name = $name;
    $this->sex = $sex;
    $this->age = $age;
  }
  function say(){
    echo " My name: " . $this->name . " , gender: " . $this->sex . " , age: " .$this->age . "<br />";
  }
  function __clone(){
    $this->name = " Li 44";  // In the copy object name Property reassignment 
    $this->age = 10;  // In the copy object age Property reassignment 
  }
}
$person1 = new Person(" Zhang 33", " Male ", 23);
$person2 = clone $person1; // Create 1 Object, and automatically calls a copy of the __clone() Method 
$person1->say();  // Call the speech mode in the original object and print all the attribute values in the original object 
$person2->say();  // Call the speaking mode in the copy object and print all the property values in the clone object 
?>

Run results:

My name: Zhang 33, gender: male, age: 23
My name: Li 44, gender: male, age: 10

3. Strengthening singleton classes: Prohibiting cloning

For an object of a class, if the "clone operator" is used, a new object exactly like the current object will be copied, and the magic method of the class will be automatically called at this time: __clone() As long as the method is in the class.

To implement a singleton class, you should "prohibit cloning" the objects of this singleton class. In PHP, in order to prevent cloning of singleton objects to break the above implementation of singleton classes, it is usually provided with an empty private ( private Modified) __clone() Method.

First of all, let's look at the effect of "not prohibiting cloning":


<?php
class SingetonBasic {
  private static $instance; // Static variables should be privatized to prevent out-of-class modification 
  private function __construct() {  // Constructor is privatized, and new objects cannot be directly created outside the class 
}
//private function __clone() {} // In __clone() Pre-use private Modification, used to prohibit cloning 
public static function getInstance() { // Common static method ,public --External interfaces, static --Access by class name instead of using objects 
  if (!(self::$instance instanceof self)) { // Private static variable $instance Empty 
    self::$instance = new self(); // Create an object as its own and assign it to a private variable $instance
  }
  return self::$instance; // Returns a private variable $instance
}
}
$a = SingetonBasic::getInstance();
$b = SingetonBasic::getInstance();
var_dump($a === $b);  // The results are: boolean true   a And b It points to the same 1 Objects 
$c = clone $a;
var_dump($a === $c); // The results are: boolean false   a And c It does not point to the same 1 Objects 
?>

The running result is

boolean true

boolean false

We "do no cloning", that is, put the above code


private function __clone() {}  // In __clone() Pre-use private Modification, used to prohibit cloning 

This line of code removes comments.

The running result is

boolean true

Fatal error: Call to private SingetonBasic::__clone()

That is, at the time of cloning, it automatically calls the __clone() But the method is private Modification, can no longer be called directly from the outside of the class, and the result is an error.

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: