使PHP数组的副本到另一个

使PHP数组的副本到另一个

本文介绍了有一个函数,使PHP数组的副本到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个函数来将PHP数组的副本复制到另一个?

Is there a function to make a copy of a PHP array to another?

我已经烧了几次试图复制PHP数组。

I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an object to a global outside it.

推荐答案

在PHP中,数组是通过拷贝分配的,而对象通过引用分配。这意味着:

In PHP arrays are assigned by copy, while objects are assigned by reference. This means that:

$a = array();
$b = $a;
$b['foo'] = 42;
var_dump($a);

将产生:

array(0) {
}

>

Whereas:

$a = new StdClass();
$b = $a;
$b->foo = 42;
var_dump($a);

产量:

object(stdClass)#1 (1) {
  ["foo"]=>
  int(42)
}

您可能会被复杂的,其是一个完全像数组一样工作的对象。作为一个对象,但它有引用语义。

You could get confused by intricacies such as ArrayObject, which is an object that acts exactly like an array. Being an object however, it has reference semantics.

编辑:@AndrewLarsson在下面的注释中提出一点。 PHP有一个称为引用的特殊功能。它们有点类似于C / C ++语言中的指针,但不完全相同。如果你的数组包含引用,那么当数组本身通过copy传递时,引用仍将解析为原始目标。这当然通常是所需的行为,但我认为值得一提。

@AndrewLarsson raises a point in the comments below. PHP has a special feature called "references". They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.

这篇关于有一个函数,使PHP数组的副本到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:34