Sobes.tech
Junior — Middle

What is the difference between data transfer by reference and by value, and how does it affect data modification inside a program?

sobes.tech AI

Answer from AI

Passing data by value means that when a variable is passed to a function, a copy of it is created. Changes inside the function do not affect the original. In PHP, this is typical for scalar types (int, string, bool) and arrays (up to PHP 7 with copying on write).

Passing by reference means that a reference to the original data is passed to the function, and any changes inside the function are reflected on the original variable. In PHP, this is implemented using an ampersand (&) before the parameter.

Example:

function addOneByValue($num) {
    $num += 1;
}

function addOneByReference(&$num) {
    $num += 1;
}

$a = 5;
addOneByValue($a); // $a remains 5
addOneByReference($a); // $a becomes 6

Thus, passing by reference allows the function to modify the passed data, while passing by value does not.