green123
green123

Reputation: 75

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);

Upvotes: 0

Views: 1440

Answers (1)

André Schild
André Schild

Reputation: 4754

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.

Upvotes: 1

Related Questions