phpfunctionvariablesreferenceglobal

PHP: Update global reference variabele inside function scrope


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:

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?


Solution

  • It's impossible to do that in PHP with only global keyword.

    This is because references in php are not same as pointers as we know them for example from C/C++.

    When you do $girl = &$anna; on line 3 it doesn't store address of $anna variable in $girl variable. Rather the new symbol $girl is created to reference same variable as symbol $anna.

    When you do global $girl, $bella; inside of a function. New local symbols $girl and $bella are created and they are made to reference their global counterpart.

    When you do $girl = &$bella; inside the function the local symbol $girl is changed to reference same variable as local symbol $bella but the global symbol $girl is not changed. After doing that both local symbols $girl and $bella are referencing same global symbol $bella.