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 $test to init by value, not by reference. The $test inside init is 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:
function init ( &$test )
{
$test['foo'] = 'bar';
$test['foo'] // evaluates to'bar'
}
Use global $test in init.
function init ()
{
global $test;
$test['foo'] = 'bar';
$test['foo'] // evaluates to'bar'
}
Or have init return the array (which means you need to do $test = init( $test );):
function init ( $test )
{
$test['foo'] = 'bar';
$test['foo'] // evaluates to'bar'
return $test;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With