php中的數組引用問題

[英]issue with array reference in php


I am trying to run following code:

我正在嘗試運行以下代碼:

$a = array('aa');

function my_func (& $m) {
    return $m;
}

$c = & my_func($a);
$c[] = 'bb';
var_dump($a);
echo '--------';
var_dump($c);

My expectation were that $a and $c would have same reference. But the result is different.

我的期望是$ a和$ c會有相同的參考。但結果卻不同。

Result i got was:

我得到的結果是:

array(1) { [0]=> string(2) "aa" } --------array(2) { [0]=> string(2) "aa" [1]=> string(2) "bb" } 

What is wrong in above piece of code?

上面的代碼有什么問題?

1 个解决方案

#1


4  

I think what you are looking for is function returning by reference (this in conjunction with passing by reference in your example).

我認為你要找的是通過引用返回的函數(這與你的例子中的引用一起傳遞)。

Here is an example:

這是一個例子:

function &my_func(&$m) {
    return $m;
}

$a = array('aa');
$c = &my_func($a);
$c[] = 'bb';

var_dump($a);
echo "---\n";
var_dump($c);

Outputs:

輸出:

array(2) {
  [0]=>
  string(2) "aa"
  [1]=>
  string(2) "bb"
}
---
array(2) {
  [0]=>
  string(2) "aa"
  [1]=>
  string(2) "bb"
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/11/15/bf30307aa7675c6a9a043ca1d19a8cf8.html



 
  © 2014-2022 ITdaan.com 联系我们: