沃梦达 / 编程问答 / php问题 / 正文

如何在 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 中创建对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 PHP 中创建对象的副本?

基础教程推荐