Novice: PHP array by reference question (by C++ programmer)
| From: | Manish Gupta | Date: | Mon, 31 Oct 2011 09:54:03 +0000 |
| Subject: | Novice: PHP array by reference question (by C++ programmer) | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-315565@lists.php.net to get a copy of this message | ||
I have a class that takes as input, an array by reference and stores it in a member variable. A method in this class later modifies the member variable (which contains reference to the array). When I access the local variable that was passed by reference to the constructor of this class object, I see the local variable hasn't changed at all. I think code will describe what words may not have:
<?php
class foo
{
public $_bar;
public function __construct(& $bar)
{
$this->_bar = $bar;} function do_your_thing() {
$temp = array(
'One' => 1,
'Two' => 2
);
$this->_bar[] = $temp;
echo('from Do_your_thing: ');
print_r($this->_bar); // ---------------- [1]
}
}
$abc = array();
$var = new foo($abc);
$var->do_your_thing();
echo('from main [local variable]: ');
print_r($abc); // ---------------- [2]
echo('from main: [object member variable] ');
print_r($var->_bar); // ---------------- [3]?> I expected the output from [1], [2] and [3] to be the same. But instead I get the following: from Do_your_thing: Array ( [0] => Array
(
[One] => 1
[Two] => 2
)
)
from main [local variable]: Array
(
)
from main: [object member variable] Array
(
[0] => Array
(
[One] => 1
[Two] => 2
)
)
What am I missing? Please help, I'm new to PHP and this is really blocking me.
Thanks
M@nish