How to return a variable by reference in php?

Member

by lizzie , in category: PHP General , 10 months ago

How to return a variable by reference in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 10 months ago

@lizzie 

In PHP, you can return a variable by reference by using the & symbol before the variable name in both the function declaration and the return statement.


Here's an example:

1
2
3
4
5
6
7
8
9
function &returnVariableByReference(&$var) {
    $var = 'Changed value';
    return $var;
}

$myVar = 'Original value';
$returnedVar = &returnVariableByReference($myVar);

echo $myVar; // Prints 'Changed value'


In this example, the & symbol is used in both the function declaration and the return statement to indicate that the variable should be returned by reference. This means that any changes made to the returned variable will also affect the original variable that was passed to the function.