是否有将 PHP 数组复制到另一个数组的功能? [英] Is there a function to make a copy of a PHP array to another?

查看:105
本文介绍了是否有将 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) {
}

鉴于:

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

产量:

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

您可能会被 ArrayObject,它是一个与数组完全一样的对象.然而,作为一个对象,它具有引用语义.

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++ 等语言中的指针,但并不完全相同.如果您的数组包含引用,那么当数组本身通过副本传递时,引用仍将解析为原始目标.这当然是通常所期望的行为,但我认为值得一提.

@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 数组复制到另一个数组的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆