search
Homephp教程php手册PHP 5.0对象模型深度探索之对象复制

PHP 5.0对象模型深度探索之对象复制

Jun 13, 2016 pm 12:29 PM
clonephpandlandcopyobjectWillEstablishexploremethodModeldepthusedefault

默认地,用__clone方法将建立一个与原对象拥有相同属性和方法的对象. 如果你想在克隆时改变默认的内容,你要在__clone中覆写(属性或方法)。

  克隆的方法可以没有参数,但它同时包含this和that指针(that指向被复制的对象)。如果你选择克隆自己,你要小心复制任何你要你的对象包含的信息,从that到this,如果你用__clone来复制,PHP不会执行任何隐性的复制,下面显示了一个用系列序数来自动化对象的例子:

复制代码 代码如下:


class ObjectTracker //对象跟踪器 

 private static $nextSerial = 0; 
 private $id; 
 private $name; 

 function __construct($name) //构造函数 
 { 
  $this->name = $name; 
  $this->id = ++self::$nextSerial; 
 } 

 function __clone() //克隆 
 { 
  $this->name = "Clone of $this->name"; 
  $this->id = ++self::$nextSerial; 
 } 

 function getId() //获取id属性的值 
 { 
  return($this->id); 
 } 

 function getName() //获取name属性的值 
 { 
  return($this->name); 
 } 


$ot = new ObjectTracker("Zeev's Object"); 
$ot2 = clone$ot; 

//输出: 1 Zeev's Object 
print($ot->getId() . " " . $ot->getName() . ""); 

//输出: 2 Clone of Zeev's Object 
print($ot2->getId() . " " . $ot2->getName() . ""); 
?>


Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment