通过值或引用传递Php

通过值或引用传递Php,php,Php,据我所知,当我按值传递数组时,将创建数组的副本。 i、 在下面的程序中,$y和$z需要与$x相同的内存。然而,内存利用率几乎没有增加。 很明显,我的理解是错误的,有人能解释原因吗 for($i=0;$i<1000000;$i++) $x[] = $i; // memory usage : 76519792 echo memory_get_usage(); function abc($y){ $y[1] = 1; //memory usage : 765

据我所知,当我按值传递数组时,将创建数组的副本。 i、 在下面的程序中,$y和$z需要与$x相同的内存。然而,内存利用率几乎没有增加。 很明显,我的理解是错误的,有人能解释原因吗

for($i=0;$i<1000000;$i++)

        $x[] = $i; // memory usage : 76519792


echo memory_get_usage(); 

function abc($y){

    $y[1] = 1; //memory usage  : 76519948 
    $z[]= $y;   //memory usage : 76520308

}

for($i=0;$i我听说php使用写时复制:

例如:

<?
for($i=0;$i<100000;$i++)
    $x[] = $i;

// we output the memory use:
echo memory_get_usage().'<br/>';  // outputs 14521040

// here we equate $y to $x, but instead of creating a copy, 
// php engine just creates a pointer to the same memory space
$y = $x;

echo memory_get_usage().'<br/>';  // outputs 14521128

// here we change something in y, now php engine 
// "creates a seperate copy" for y and makes the change
$y[1]=8;

echo memory_get_usage().'<br/>';  // outputs 23569904

?>

和函数调用的类似行为:

<?
for($i=0;$i<100000;$i++)
    $x[] = $i;

echo memory_get_usage().'<br/>'; /* 14524968 */

function abc($y){
    echo memory_get_usage().'<br/>'; /* 14524968 */
    $y[1] = 1;
    echo memory_get_usage().'<br/>'; /* 23573752 */
    $z[]= $y;  
    echo memory_get_usage().'<br/>'; /* 23574040 */

}
abc($x);
echo memory_get_usage().'<br/>'; /* 14524968 */
?>


PS:我正在windows上测试这一点,可能在linux上有所不同

我相信php实际上不会复制数据,除非您修改任何一个实例。暂时性的向上投票,因为这是正确的答案。不过您应该更好地表述这一点。检查第$y[1]行=$y;静态内存增加hardly@chicharitoZend引擎比你想象中的WRT内存更智能。你在那里只修改了一条数据,所以实际上没有太多事情要做。@daghan奇怪,在我的例子中是$y[1]=11;//内存使用率:76519948没有增加内存,而您的情况是这样。@deceze:我在windows上测试过,这可能是个问题