Home > Backend Development > PHP Tutorial > What is php clone object? How is it achieved?

What is php clone object? How is it achieved?

伊谢尔伦
Release: 2023-03-14 09:10:02
Original
1399 people have browsed it

Sometimes we need to use two or more identical objects in a project. If you use the "new" keyword to create the object again, assign the value The same attribute is cumbersome and error-prone, so it is very necessary to completely clone an identical object based on an object, and after cloning, the two objects will not interfere with each other.
In PHP5 we use the "clone" keyword to clone objects;

<?php 
class Person{ 
//下面是人的成员属性 
var $name; //人的名子 
var $sex; //人的性别 
var $age; //人的年龄 
//定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值 
function construct($name="", $sex="", $age=""){ 
$this->name=$name; 
$this->sex=$sex; 
$this->age=$age; 
} 
//这个人可以说话的方法, 说出自己的属性 
function say() { 
echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."<br>"; 
} 
} 
$p1=new Person("张三", "男", 20); 
//使用“clone”克隆新对象p2,和p1对象具有相同的属性和方法。 
$p2=clone $p1; 
$p2->say(); 
?>
Copy after login

PHP5 defines a special method name "clone()" method, which is automatically called when an object is cloned. Use The "clone()" method will create an object with the same properties and methods as the original object. If you want to change the
content of the original object after cloning, you need to rewrite the original properties and methods in clone(), "clone ()" method can have no parameters, it automatically contains two pointers $this and $that, $this points to the copy, and $that points to the original;

<?php
  //定义类staff,其中包括属性id和name
  class staff 
  {
   private $id;
   private $name;
   function setID($id) 
   {
     $this->id = $id;
   }
   function getID() 
   {
     return $this->id;
   }
   function setName($name) 
   {
     $this->name = $name;
   }
   function getName() 
   {
     return $this->name;
   }
   //这里是clone函数
   function clone()
   {
    $this->id = $this->id + 1;
   }
  }
  //创建一个新的staff对象并初始化
  $ee1 = new staff();
  $ee1->setID("145");
  $ee1->setName("Simon");
  //克隆一个新的对象
  $ee2 = clone $ee1;
  //重新设置新对象的ID值
  //$ee2->setID("146");
  //输出ee1和ee2
  echo "ee1 ID: ".$ee1->getID()."<br>";
  echo "ee1 Name: ".$ee1->getName()."<br>";
  echo "ee2 ID: ".$ee2->getID()."<br>";
  echo "ee2 Name: ".$ee2->getName()."<br>";
?>
Copy after login

The above is the detailed content of What is php clone object? How is it achieved?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template