简体   繁体   中英

Global variable vs passing by reference in function (php)

What is better and why?

1)- What variant: Global variable vs passing by reference

/* 1 example */
$val = 1;
function add1(){
    global $val;
    $val++;
}
add1();
var_dump($val);

/* 2 example */
$val = 1;
function add2(&$val){
    $val++;
}
add2($val);
var_dump($val);

2)- What variant: *"Return" vs passing by reference

/* 3 example */
$val = 1;
function add3(&$val){
    $val++;
}
add3($val);
var_dump($val);

/* 4 example */
$val = 1;
function add4($val){
    $val++;
    return $val;
}
$val = add4($val);
var_dump($val);

It always depends what you intend to do.

But commonly Example 2 is much better than 1. Functions should not modify global variables, it's called a side effect which is very hard to control. The call with reference ich much more clear to the code readers.

Also same for the second part, Example 4 is better, since you can use the add4() function with any variable.

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