PHP functions can be externally modified by returning a variable reference by using & as the function parameter type declaration. The following are examples of modifying variables through pass by value and pass by reference: Pass by value: The variable value does not change Pass by reference: The variable value does change
PHP Function How to return a reference
PHP functions can allow code outside the function to modify the variable value by returning a variable reference. This can be achieved by using two symbols (&) for the function parameter type declaration.
Syntax:
function &getVariableReference(...$args) { // ... return $variable; }
Practical case:
The following are examples of changing variables by value passing and reference passing:
Pass by value:
$x = 10; function changeValue($value) { $value++; } changeValue($x); echo $x; // 输出 10,变量值未更改
Pass by reference:
$x = 10; function &changeValueReference(&$value) { $value++; } changeValueReference($x); echo $x; // 输出 11,变量值已更改
Notes:
The above is the detailed content of How do PHP functions return references?. For more information, please follow other related articles on the PHP Chinese website!