Home >Backend Development >PHP Tutorial >How Can I Create True Copies of Objects in PHP?

How Can I Create True Copies of Objects in PHP?

DDD
DDDOriginal
2024-11-28 09:40:11204browse

How Can I Create True Copies of Objects in PHP?

Copying Objects in PHP: Understanding Pass by Reference and Using 'Clone'

Despite the belief that objects are passed by reference in PHP, assignment operators do not create copies. This behavior is demonstrated in the following example code:

class A {
    public $b;
}

function set_b($obj) { $obj->b = "after"; }

$a = new A();
$a->b = "before";
$c = $a;

set_b($a);

print $a->b;
print $c->b;

In this case, both print statements will output "after," indicating that the object has been modified by the set_b() function despite being passed as an argument.

To create a copy of an object in PHP, you can use the clone operator introduced in PHP 5 :

$objectB = clone $objectA;

This operation creates a new object that is independent of the original object. Any changes made to one object will not affect the other.

It's important to note that only objects are passed by reference in PHP. Variables of other types, such as arrays, strings, and integers, are passed by value. This means that assigning these variables to other variables creates a new instance of the variable, rather than a reference to the original variable.

The above is the detailed content of How Can I Create True Copies of Objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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