How to Pass PHP Variables by Reference

In PHP, you can pass variables by reference instead of by value using the ampersand (&) symbol. This allows you to modify the original variable within a function or method. There are primarily two ways to pass PHP variables by reference:

  • Using the ampersand in the function/method declaration

  • Using the ampersand when passing the variable to a function/method

Using the Ampersand in the Function/Method Declaration

To pass variables by reference using the ampersand in the function/method declaration, you need to include the ampersand symbol before the parameter name in the function/method definition. This indicates that the parameter should be passed by reference, allowing modifications to the original variable

<?php
function modifyValue(&$variable) {
    $variable += 10;
}

$myVariable = 5;
modifyValue($myVariable);
echo $myVariable;
?>
15

In the above code, the function modifyValue takes a parameter $variable with an ampersand before the variable name, indicating that it is passed by reference. Within the function, the value of $variable is modified by adding 10 to it. When the function is called with $myVariable as an argument, the original variable is passed by reference, allowing the function to modify its value directly.

Using the Ampersand when Passing the Variable (Deprecated)

In older PHP versions, you could pass variables by reference using the ampersand symbol when calling the function. However, this method has been deprecated since PHP 5.3.0 and removed in PHP 7.0

<?php
// This syntax is DEPRECATED and will cause errors in modern PHP
function modifyValue($variable) {
    $variable += 10;
}

$myVariable = 5;
modifyValue(&$myVariable); // This causes a fatal error in PHP 7.0+
echo $myVariable;
?>

The above code will produce a fatal error in modern PHP versions because passing by reference at call time is no longer supported. You should always use the ampersand in the function declaration instead.

Comparison

Method Status Usage
Ampersand in function declaration Current function test(&$var)
Ampersand at call time Deprecated/Removed test(&$var)

Conclusion

To pass variables by reference in modern PHP, always use the ampersand symbol in the function declaration, not when calling the function. This ensures the variable is explicitly passed by reference and allows you to modify the original variable within the function.

Updated on: 2026-03-15T10:29:01+05:30

857 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements