Function calls in PHP can be passed by value or by reference. The default is to pass by value, the function receives a copy of the parameter, and modifications to it do not affect the original value. Pass by reference is declared by adding the & symbol before the parameter, and the function directly modifies the passed variable. Passing by reference is useful when you need a function to modify an external variable, such as an array element.
In PHP, by default, function calls Use value passing. This means that when a value is passed to a function as an argument, the function will get a copy of the value. Any changes made to this copy will not affect the original value.
function addValue($number) { $number += 10; } $value = 10; addValue($value); echo $value; // 输出:10
As shown in the above example, when$value
is passed to theaddValue
function, the function gets a copy of the variable. Modifications within the function only affect the copy, not the original variable.
Sometimes, we need a function to directly modify the original variable. In this case, pass by reference can be used. To declare a reference, add a&
symbol before the parameter type declaration.
function addReference(&$number) { $number += 10; } $value = 10; addReference($value); echo $value; // 输出:20
As shown in the above example, the$number
parameter of theaddReference
function is declared as a reference. This means that the function will directly modify the passed variable.
Using passing by reference can simplify certain tasks. For example, we have an array containing user data and need to modify it in a function.
$users = [ [ 'id' => 1, 'name' => 'John Doe', ], ]; function changeName(&$user, $newName) { $user['name'] = $newName; } changeName($users[0], 'Jane Doe'); echo $users[0]['name']; // 输出:Jane Doe
By declaring the$user
parameter as a reference, thechangeName
function can directly modify the original element in the array.
Understanding pass-by-value and pass-by-reference in PHP is crucial to writing efficient and maintainable code. By using pass-by-reference, we can avoid unnecessary copying of variables and directly modify variables outside the function.
The above is the detailed content of Demystifying pass-by-value and pass-by-reference in PHP function calls. For more information, please follow other related articles on the PHP Chinese website!