PHP: Only variable references should be returned by reference

There is a Mobile Optimized version of this page (AMP). Open Mobile Version.

Pulling your hair out over this Notice message? Well here is an explanation for why you are getting this and how you can avoid it.

Take a look at the following code:

<?php
class myClass {
    public $var = 1;
 
    public function &getVar() {
        return($this->var);
        }
}
 
$obj = new myClass;
$value = &$obj->getVar();
?>

Now this code works completely fine, apart from every time it hits the “return” statement it chucks out a weird Notice error: Only variable references should be returned by reference.

But what does that actually mean? … Basically the return statement is returning the result of the variable and not the reference because of the () brackets around the variable.

so to return correctly by reference you would do this instead:

<?php
class myClass {
    public $var = 1;
 
    public function &getVar() {
        return $this->var;
        }
}
 
$obj = new myClass;
$value = &$obj->getVar();
?>

Kicking yourself now? Yes it is that easy…

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips