简体   繁体   中英

Assign array value by function return reference

I want to assign a value to an array element, which is returned by a function with a reference argument. The code:

function f(&$y) {
    return $y;
}

$y = '';

$x = array(
        'a' => 1,
        'b' => 2,
        'c' => f($y)
        );
var_dump($x); // 'c' is empty

$y = 3;

var_dump($x); // 'c' is still empty

I'm pretty sure I got the whole reference thing all wrong in this case. Still not working even if I try to return by reference like function &f(&y) {} .

If you want this with a function call (you could as well alias $y directly), then you would need to use return by reference ( see: Returning References ), see the & sign before the function name:

function &f(&$y) {
    return $y;
}

Also you need to alias that reference (which needs some special treatment to make the PHP parser allow this):

$y = '';

$x = array(
        'a' => 1,
        'b' => 2,
        'c' => &${${''}=&f($y)?!1:!1},
);

See it in action .

You should try

$x = array(
    'a' => 1,
    'b' => 2,
    'c' => &$y
    );

First of all, a warning: this kind of code is way too confusing and you should only do it if threatened at gunpoint. Your future self will hate you when they have to debug code like this.

That said, to make this work you need "moar references":

function &f(&$y) { // two ref-signs here...
    return $y;
}

$y = '';
$x = array(
    'a' => 1,
    'b' => 2,
    'c' => &f($y) // ..and one more here
);

However, the above still does not compile (I have no idea why, will investigate when time permits) because it seems that you are not allowed to do that when in the middle of creating an array. But this works:

$y = '';
$x = array('a' => 1, 'b' => 2);
$x['c'] = &f($y); // seems this guy needs to be alone

$y = 3;
print_r($x);

See it in action .

According to a quick glance at the PHP manual, it looks like your array() syntax is missing a comma.

$x = array(
    'a' => 1,
    'b' => 2,
    'c' => f($y)
    );

Should actually be

$x = array(
    'a' => 1,
    'b' => 2,
    'c' => f($y),
    );

Source: http://php.net/manual/en/language.types.array.php

I haven't written PHP in years, I'm just going by the example the author put.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM