Table of Contents
PHP object-oriented cloning
Home Backend Development PHP Tutorial PHP object-oriented cloning_PHP tutorial

PHP object-oriented cloning_PHP tutorial

Jul 13, 2016 am 10:01 AM
object

PHP object-oriented cloning

One of the biggest disadvantages of PHP4 object-oriented is that it treats objects as another data type, which makes many common OOP methods unusable, such as design patterns. These OOP methods rely on passing objects to other class methods as references, rather than as values. Fortunately PHP solves this problem. All objects are now treated as references by default. But because all object pairs are treated as references rather than values, it is now harder to copy objects. If you try to copy an object, this will point to the address of the original object. To solve the duplication problem, PHP provides a method to clone the display object.

Examples are as follows:

First introduce the use of clone keyword to clone objects:

<!--?php
    class TestClone
    {
    	public  $name;
    	public $num;
    	
    	function setName($na)
    	{
    		$this--->name = $na;
    	}
    	
    	function getName()
    	{
    		return $this->name;
    	}
    	
    	function setNum($nu)
    	{
    		$this->num = $nu;
    	}
    	function getNum()
    	{
    		return $this->num;
    	}
    }
    
    $test = new TestClone();
    $test->setName("tianxin");
    $test->setNum(123456);
    echo $test->getName();
    echo $test->getNum()."
";
    
    $test2 = clone $test;
    $test2->setName("liwei");
    echo $test->getName();
    echo $test->getNum()."
";
    
    echo $test2->getName();
    echo $test2->getNum();
    
?>
Copy after login
Running results:

tian123456
tian123456
xia123456
Copy after login

From the running results, we can see that if test2 does not modify the name. Although the two objects test and test2 are different objects, they have the same attributes, and changing the attributes of the test2 object will not affect the attributes of the test object. Therefore, it can be concluded that cloning is passing by value, not a simple reference.

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

<!--?php
    class TestClone
    {
    	public  $name;
    	public $num;
    	
    	function setName($na)
    	{
    		$this--->name = $na;
    	}
    	
    	function getName()
    	{
    		return $this->name;
    	}
    	
    	function setNum($nu)
    	{
    		$this->num = $nu;
    	}
    	function getNum()
    	{
    		return $this->num;
    	}
    	
    	function __clone()
    	{
    		$this->name = "huang";
    	}
    }
    
    $test = new TestClone();
    $test->setName("tian");
    $test->setNum(123456);
    echo $test->getName();
    echo $test->getNum()."
";
    
    $test2 = clone $test;
//     $test2->setName("xia");
    echo $test->getName();
    echo $test->getNum()."
";
    
    echo $test2->getName();
    echo $test2->getNum();
    
?>
Copy after login

Running results:

tian123456
tian123456
huang123456
Copy after login

<!--?php
class Person {
    // 下面是人的成员属性
    var $name; // 人的名字
    var $sex; // 人的性别
    var $age; // 人的年龄
              // 定义一个构造方法参数为属性姓名$name、性别$sex 和年龄$age 进行赋值
              // function __construct($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 . "
";
    }
    // 对象克隆时自动调用的方法, 如果想在克隆后改变原对象的内容,需要在__clone()中重写原来的属性和方法。
    function __clone() {
        // $this 指的复本p2, 而$that 是指向原本p1,这样就在本方法里,改变了复本的属性。
        $this->name = "我是复制的张三$that->name";
        // $this->age = 30;
    }
}
$p1 = new Person ( "张三", "男", 20 );
$p2 = clone $p1;
$p1->say ();
$p2->say ();
?>
Copy after login

Result after running:

我的名字叫:张三 性别:男 我的年龄是:20
我的名字叫:我是复制的张三 性别:男 我的年龄是:20
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/972221.htmlTechArticlePHP object-oriented clone One of the biggest disadvantages of object-oriented php4 is that it treats objects as another data type , which makes many common OOP methods unusable, such as design patterns. These O...
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Convert an array or object to a JSON string using PHP's json_encode() function Convert an array or object to a JSON string using PHP's json_encode() function Nov 03, 2023 pm 03:30 PM

JSON (JavaScriptObjectNotation) is a lightweight data exchange format that has become a common format for data exchange between web applications. PHP's json_encode() function can convert an array or object into a JSON string. This article will introduce how to use PHP's json_encode() function, including syntax, parameters, return values, and specific examples. Syntax The syntax of the json_encode() function is as follows: st

Source code exploration: How are objects called in Python? Source code exploration: How are objects called in Python? May 11, 2023 am 11:46 AM

Wedge We know that objects are created in two main ways, one is through Python/CAPI, and the other is by calling a type object. For instance objects of built-in types, both methods are supported. For example, lists can be created through [] or list(). The former is Python/CAPI and the latter is a calling type object. But for instance objects of custom classes, we can only create them by calling type objects. If an object can be called, then the object is callable, otherwise it is not callable. Determining whether an object is callable depends on whether a method is defined in its corresponding type object. like

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

Use Python's __contains__() function to define the containment operation of an object Use Python's __contains__() function to define the containment operation of an object Aug 22, 2023 pm 04:23 PM

Use Python's __contains__() function to define the containment operation of an object. Python is a concise and powerful programming language that provides many powerful features to handle various types of data. One of them is to implement the containment operation of objects by defining the __contains__() function. This article will introduce how to use the __contains__() function to define the containment operation of an object, and give some sample code. The __contains__() function is Pytho

Use Python's __le__() function to define a less than or equal comparison of two objects Use Python's __le__() function to define a less than or equal comparison of two objects Aug 21, 2023 pm 09:29 PM

Title: Using Python's __le__() function to define a less than or equal comparison of two objects In Python, we can define comparison operations between objects by using special methods. One of them is the __le__() function, which is used to define less than or equal comparisons. The __le__() function is a magic method in Python and is a special function used to implement the "less than or equal" operation. When we compare two objects using the less than or equal operator (&lt;=), Python

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values ​​are passed and object references are passed.

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

See all articles