On my PHP web-page I have a global array:
$test = array();
Then I invoke this function:
function f ()
{
global $test;
init( $test );
$test['foo'] // Error: undefined index "foo"
}
which in turn invokes this function:
function init ( $test )
{
$test['foo'] = 'bar';
$test['foo'] // evaluates to'bar'
}
As you can see, I get an error. The “foo” field that I’ve added to the array inside init() did not persist. Why does this happen? I thought I was mutating the global $test inside init(), but it seems that I’m not doing that. What’s going on here, and how can I set a “foo” field inside init() that persists?
You are passing
$testtoinitby value, not by reference. The$testinsideinitis a local variable that just happens to contain the value of the global$test.You either need to pass the array by reference, by changing the
init‘s function signature:Use
global $testininit.Or have
initreturn the array (which means you need to do$test = init( $test );):