Home > Backend Development > PHP Tutorial > Section 5--Clone--ClassesandObjectsinPHP55_PHP Tutorial

Section 5--Clone--ClassesandObjectsinPHP55_PHP Tutorial

WBOY
Release: 2016-07-13 17:23:58
Original
867 people have browsed it

/* +-------------------------------------------------- --------------------------------+ | = This article is read by Haohappy> | = Classes and Objects 1 Chapter's notes | = Translation + personal experience | = To avoid unnecessary trouble, please do not reprint, thank you | = Criticisms and corrections are welcome, and I hope to make progress together with all PHP enthusiasts! +------- -------------------------------------------------- -----------------------+ */ Section 5 - Cloning The object model in PHP5 calls objects by reference, but sometimes you may want to create an object A copy of the original object, and hope that changes to the original object will not affect the copy. For this purpose, PHP defines a special method called __clone. Like __construct and __destruct, there are two underscores in front of it. By default, Using the __clone method will create an object with the same properties and methods as the original object. If you want to change the default content when cloning, you have to override (properties or methods) in __clone. The clone method can have no parameters, But it contains both this and that pointers (that points to the object being copied). If you choose to clone yourself, you need to be careful about copying any information you want your object to contain from that to this. If you use __clone to copy. PHP does not perform any implicit copying, the following shows an example of automating objects using serial numbers: name = $name; $this->id = ++self::$nextSerial; } function __clone() //Clone { $this->name = "Clone of $that->name"; $this->id = ++self::$nextSerial; } function getId() //Get the value of the id attribute { return($ this->id); } function getName() //Get the value of the name attribute { return($this->name); } } $ot = new ObjectTracker("Zeevs Object"); $ot2 = $ot->__clone (); //Output: 1 Zeevs Object print($ot->getId() . " " . $ot->getName() . "


"); //Output: 2 Clone of Zeevs Object print($ot2->getId() . " " . $ot2->getName() . "
"); ?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/532190.htmlTechArticle/* +--------------------- -------------------------------------------------- --------+ | = This article is read by Haohappy> | = Notes from the Chapter Classes and Objects| = Translation + personal experience...
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