I’m trying to change a global value that is currently a reference to another value. My current implementation doesn’t work:
$anna = array('Name' => "Anna");
$bella = array('Name' => "Bella");
$girl = &$anna;
function change(){
global $girl, $bella;
$girl = &$bella;
// $girl['Name'] is now 'Bella'
output_girl(); // This still outputs 'Anna'
}
function output_girl(){
global $girl;
echo $girl['Name'];
}
change();
// What do we want to see?
echo $anna['Name']; // Should still be 'Anna'
echo $bella['Name']; // Should still be 'Bella'
echo $girl['Name']; // Should now be 'Bella' (in above example this will still be 'Anna')
Important notes:
- A workaround with a return value like
$girl = &change();
is not a solution to my problem. It’s important that the global$girl
is changed before the end of thechange()
function. (Reason being this is a problem inside a complex project with nested function calls all wanting to use the same global variables.) - I am aware a workaround could be coded using the
$GLOBALS
array. However, I am specifically interested if this problem can be solved using theglobal
keyword as seen in the example code. And if not, to know why this isn’t possible in PHP. - Removing the
&
to make it$girl = $bella
is also not a solution. The global $girl object needs to always be a reference to the original arrays defined at the start of the script. We cannot ever make copies / break references.
Question: Is this an impossibility in PHP when I use the global
keyword? If so, can someone explain why? If not, can someone explain how to make this work?