是否有将 PHP 数组复制到另一个数组的功能?

Is there a function to make a copy of a PHP array to another?(是否有将 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) {
}

鉴于:

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

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

相关文档推荐

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)