简体   繁体   中英

PHP: Passing array by reference fail

I've the following code function:

function foo(&$vett) {

    $vettore = $vett;

    $vettore[] = "ciao";

    var_dump($vettore);
}

$v = array();

foo($v);

var_dump($v);

When I dump the final array is empty. Have you any idea of what could be?

Because $v never modified. Inside the function you assign the variable into another variable. So nothing ever happen to the old $vett

try something like:

function foo(&$vett) {
    $vett[] = "ciao";
    echo __LINE__;
    var_dump($vett);
}

$v = array();
foo($v);
var_dump($v);

Correct version is:

function foo(&$vett) {
    $vett[] = "ciao";
}

$v = array();
foo($v);
var_dump($v);

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