1

What do this reference symbol (&) do in &methodName() method?

Is it necessary?

Is this called a reference by method?

class TestClass
{
    private $value;
    public function __construct()
    {
        $this->value = 5;
    }
    public function &methodName(){
        return $this->value;
    }
}
echo (new TestClass())->methodName();  //Outputs 5;
Zombie Chibi XD
  • 370
  • 3
  • 17
  • It's a reference to the current object, it's most commonly used in object oriented code. Show this answer [link](https://stackoverflow.com/questions/1523479/what-does-the-variable-this-mean-in-php) – SwissCodeMen Mar 11 '20 at 22:26
  • 1
    https://www.php.net/manual/en/language.references.return.php – AbraCadaver Mar 11 '20 at 22:27

1 Answers1

3

It means that the method returns a reference. If you then assign that to a reference variable outside the method, updating the variable will update the property.

class TestClass
{
    private $value;
    public function __construct()
    {
        $this->value = 5;
    }
    public function &refMethod(){
        return $this->value;
    }
    public function valueMethod() {
        return $this->value;
    }
    public function printValue() {
        echo $this->value . "<br>";
    }
}
$c = new TestClass();
$var1 = &$c->valueMethod();
$var1 = 10;
$c->printValue(); // prints 5
$var = &$c->refMethod();
$var = 20;
$c->printValue(); // prints 20
Barmar
  • 741,623
  • 53
  • 500
  • 612