有没有做一个PHP数组的一个拷贝到另一个函数? [英] Is there a function to make a copy of a PHP array to another?

查看:210
本文介绍了有没有做一个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天全站免登陆