Is there a function to make a copy of a PHP array to another?(是否有将 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 数组复制到另一个数组的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有将 PHP 数组复制到另一个数组的功能?
基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
