如何在 PHP 中创建对象的副本?

How do I create a copy of an object in PHP?(如何在 PHP 中创建对象的副本?)
本文介绍了如何在 PHP 中创建对象的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在 PHP 中对象是通过引用传递的.甚至赋值运算符似乎也没有创建 Object 的副本.

It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.

这是一个简单的、人为的证明:

Here's a simple, contrived proof:

<?php

class A {
    public $b;
}


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

$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.

set_b($a);

print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'

?>

在这两种打印情况下,我都得到了之后"

In both print cases I am getting 'after'

那么,我如何将 $a 通过值而不是引用传递给 set_b()?

So, how do I pass $a to set_b() by value, not by reference?

推荐答案

在 PHP 5+ 中,对象是通过引用传递的.在 PHP 4 中,它们是按值传递的(这就是为什么它在运行时通过引用传递,这已被弃用).

In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).

您可以使用 PHP5 中的克隆"运算符来复制对象:

You can use the 'clone' operator in PHP5 to copy objects:

$objectB = clone $objectA;

此外,它只是通过引用传递的对象,而不是您在问题中所说的所有内容......

Also, it's just objects that are passed by reference, not everything as you've said in your question...

这篇关于如何在 PHP 中创建对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)