PHP数组复制值​​或引用赋值? [英] php array assign by copying value or by reference?

查看:180
本文介绍了PHP数组复制值​​或引用赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/2030906/are-arrays-in-php-passed-by-value-or-by-reference\">are在PHP数组按​​值或按引用传递?


听说PHP可以选择如何分配阵列,取决于数组的大小。
它可以通过复制值(任意标型)或引用赋值。

PHP总是通过复制的值,因为它在手册说分配数组变量。

或者也可以通过引用赋值。 ?

 &LT; PHP $ a =阵列(1,2,3); ?&GT;


解决方案

除非你引用一个已经存在的东西你不能引用赋值的东西。同样,你不能复制的东西不存在。

所以这code:

  $ a =阵列(1,2,3);

...既不副本或引用 - 它只是创建一个新的数组值填充它,因为值实际指定

不过,这code:

  $ X = 1;
$ Y = 2;
$ Z = 3;
$ a =阵列($ X,$ Y,$ Z);

...拷贝从 $ X $ Y的值到一个数组 1 。用于初始化数组值变量中仍然存在自己的权利,并可以修改或破坏而不阵列中影响的值。

这code:

  $ X = 1;
$ Y = 2;
$ Z = 3;
$ A =阵列(安培; $ X,和放大器; $ Y,放大器; $ Z);

...创建于 $引用数组X $ Y $ Z而言(注意&安培; )。如果,运行此code后,我修改 $ X - 比方说,我给它的值4 - 它也将修改数组中的第一个值。所以,当你使用数组, $ a [0] 现在将包含 4

请参阅本手册的这一部分如何参考的更多信息在PHP中工作。


1 根据不同的类型和用作阵列成员变量的值,复制操作可能不会,即使在通过价值分配的分配时发生。内部PHP使用写入时复制在许多情况下,尽可能为性能和内存效率的原因。然而,在你的code的环境行为方面,你可以把它当作一个简单的复制。

Possible Duplicate:
are arrays in php passed by value or by reference?

I heard that PHP can select how to assign arrays, depends on array size. It can assign by copying value (as any scalar type) or by reference.

PHP always assign array to variables by copying a value, as it says in manual.

Or it can assign by reference. ?

<?php $a = array(1,2,3); ?>

解决方案

You can't assign something by reference unless you are referencing something that already exists. Equally, you can't copy something that doesn't exist.

So this code:

$a = array(1,2,3);

...neither copies or references - it just creates a new array fills it with values, because the values were specified literally.

However, this code:

$x = 1;
$y = 2;
$z = 3;
$a = array($x,$y,$z);

...copies the values from $x, $y and $z into an array1. The variables used to initialise the array values still exist in their own right, and can be modified or destroyed without affecting the values in the array.

This code:

$x = 1;
$y = 2;
$z = 3;
$a = array(&$x,&$y,&$z);

...creates an array of references to $x, $y and $z (notice the &). If, after running this code, I modify $x - let's say I give it a value of 4 - it will also modify the first value in the array. So when you use the array, $a[0] will now contain 4.

See this section of the manual for more information of how reference work in PHP.


1 Depending on the types and values of the variables used as the array members, the copy operation may not happen at the time of the assignment even when assigned by-value. Internally PHP uses copy-on-write in as many situations as possible for reasons of performance and memory efficiency. However, in terms of the behaviour in the context of your code, you can treat it as a simple copy.

这篇关于PHP数组复制值​​或引用赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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