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.
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?
George Cummins
29k8 gold badges74 silver badges91 bronze badges
asked Nov 15, 2011 at 18:54
1 Answer 1
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"
}
answered Nov 15, 2011 at 19:05
-
I dint know about returning by reference in php. Thanks. Coming from a non-php background, this is really different for me. And i fear, i dont introduce some unintentional bugs. :(Ashish– Ashish2011年11月15日 19:14:31 +00:00Commented Nov 15, 2011 at 19:14
Explore related questions
See similar questions with these tags.
lang-php