---
title: "php如何真“拷贝”一个数组"
author: "web001"
date: "2012-12-18T15:03:35Z"
tags: []
categories: ["编程语言"]
slug: "php"
draft: false
lastmod: "2012-12-18T17:29:31Z"
id: 1749671
url: "https://web001.iteye.com/blog/1749671"
---

本文翻译改编自：[http://stackoverflow.com/questions/1532618/is-there-a-function-make-a-copy-of-a-php-array-to-another](http://stackoverflow.com/questions/1532618/is-there-a-function-make-a-copy-of-a-php-array-to-another)

原文链接：[http://www.tjwzjs.cn/news/knowledge/2012/1218/function-copy-a-array-to-another.html](http://www.tjwzjs.cn/news/knowledge/2012/1218/function-copy-a-array-to-another.html "php如何“深拷贝”一个数组")

 

问：“如何在php中实现数组的拷贝？php数组是基于值拷贝还是引用拷贝呢？”

 

谢谢 @[jamcode](http://jamcode.iteye.com/ "jamcode") 的提醒，我对原文理解犯了一个很大的错误，附原文：

 

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

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中如何实现这种拷贝呢？

下面写一个简单的拷贝代码：

$a = array();

$b = $a;

$b\['foo'] = 42;

var\_dump($a);

当我们运行这段代码时，得到

array(0) {

}

可见，我们修改了B的值，但是A却没有相应的改变。于是我们换一段代码试试：

$a = new StdClass();

$b = $a;

$b-&gt;foo = 42;

var\_dump($a);

此次的输出结果变成了：

object(stdClass)#1 (1) {

  \["foo"]=&gt;

  int(42)

}

[ArrayObject](http://www.php.net/~helly/php/ext/spl/classArrayObject.html) 的行为虽然是一个数组，但是他确实是一个对象，它是通过传递引用实现赋值的。