Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The field that I set on an global array does not persist

Tags:

php

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?

like image 693
Šime Vidas Avatar asked Nov 22 '25 01:11

Šime Vidas


1 Answers

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;
}
like image 102
Rocket Hazmat Avatar answered Nov 23 '25 20:11

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!