PHP Return by Reference

In PHP, a function can return a reference instead of a value copy. This is useful when you want to allow external code to modify the original variable inside the function. To define a function that returns by reference, prefix its name with the & symbol.

Syntax

function &functionName() {
    // function body
    return $variable; // returns reference to $variable
}

$ref = &functionName(); // assign by reference

Function Returning Reference

The following example demonstrates a function that returns a reference to a static variable −

<?php
function &myfunction(){
    static $x = 10;
    echo "x Inside function: " . $x . "
"; return $x; } $a = &myfunction(); // contains reference to $x in function echo "returned by reference: " . $a . "
"; $a = $a + 10; // increments variable inside function too $a = &myfunction(); ?>
x Inside function: 10
returned by reference: 10
x Inside function: 20

Method Returning Reference

A class method can also return by reference, enabling modification of private instance variables from outside the class −

<?php
class MyClass {
    private $val;
    
    function __construct($x) {
        $this->val = $x;
    }
    
    function &getByRef() {
        return $this->val;
    }
    
    function getByVal() {
        return $this->val;
    }
}

$a = new MyClass(10);
$b = &$a->getByRef();
$b = 100; // modifies private property through reference

echo "Value of private property: " . $a->getByVal();
?>
Value of private property: 100

Key Points

  • Use & before function name to return by reference
  • Assign returned reference using $var = &function()
  • Changes to the reference variable affect the original variable
  • Useful for modifying private class properties externally

Conclusion

Return by reference allows functions and methods to provide direct access to variables, enabling external modification. This is particularly useful for accessing private class properties or maintaining state in static variables.

Updated on: 2026-03-15T09:15:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements