Reputation: 36659
In the below, I set a reference to the $myarray array with it's own key. The reference is respected within the function that calls it, but if I call the same array variable outside of the function, the reference is lost.
$myarray = array("level1" => array("level2" => array("level3" => "value")));
function test(){
global $myarray;
$myarray =& $myarray["level1"];
print_r($myarray); //returns "Array ( [level2] => Array ( [level3] => value ) )"
}
test();
echo "<br>";
print_r($myarray); //returns "Array ( [level1] => Array ( [level2] => Array ( [level3] => value ) ) )"
Do PHP references not get hoisted up to the global scope if they are defined within a function?
Upvotes: 0
Views: 80
Reputation: 36659
The reason the reference was lost outside of the function is because the $myarray global variable inside of the function is actually itself a reference to the $myarray array variable outside of the function. When you change the reference inside of the function and point it to a key inside of itself, only the "new" reference that you instantiated with the global keyboard is changed. The actual variable outside of the function is not modified.
Upvotes: 0
Reputation: 704
creating reference itself means you are creating a alias or say another instance of it. so now that behavior is both technically and literally correct. because you created instance inside a function so that overrides the GLOBAL concept.
instead of $myarray = &$myarray["level1"];
if you would have used $myarray = $myarray["level1"];
then you would have got the desired result.
Upvotes: 1
Reputation: 76656
Inside the function, you're doing $myarray = & $myarray["level1"]
-- when you do this, you're assigning the level1
sub-array to $myarray
. The $myarray
variable exists only inside the function scope, so when you try to print_r()
it outside the function, it'll just show the content of the variable defined in the global scope.
If you want to be able to modify the original array, then you need to pass it by reference:
$myarray = array("level1" =>
array("level2" =>
array("level3" => "value"))
);
function test(& $myarray){
$myarray = $myarray["level1"];
print_r($myarray);
}
test($myarray);
print_r($myarray);
This will output:
Array ( [level2] => Array ( [level3] => value ) )
Array ( [level2] => Array ( [level3] => value ) )
Upvotes: 0