I’m currently studying functions and variable scope in PHP.

I learned that we can modify the value of a variable defined outside a function using two different approaches. Both seem to achieve the same result: modifying the original variable’s value.

Passing by Reference
Using the & symbol to pass a variable by reference, allowing the function to modify it directly:

$val = 10; function addByRef(&$num) { $num += 5; } addByRef($val); echo $val; // Output: 15

Global Variables
Using the global keyword to access and modify the external variable:

$val = 10; function addByGlobal() { global $val; $val += 5; } addByGlobal(); echo $val; // Output: 15 as well

Since using global allows accessing and modifying the variable from anywhere, why do we even need the concept of passing by reference in the first place?

Are there specific cases where using references is necessary or preferable over using global?

Is there any difference between them in terms of performance or code structure?

Please don't provide any answers without your Resources, that's very important!!!!

Jone Doe's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.