使用或不使用函数返回引用

Are there any actual difference between the two ways to get the value by reference?

Way 1

<?php
class foo {
    public $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue();
// $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;
// prints the new value of $obj->value, i.e. 2.
?>

Way 2

<?php
class foo {
    public $value = 42;
    public function getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->value;
$obj->value = 2;
echo $myValue; 
?>

In both cases 2 is printed. So why does one need the getValue() function then? The first example is taken from the PHP Manual.

You need the first approach if class fields don't have a modifier 'public'. In this case you can't get a reference to the field outside the class. See example:

<?php

class foo
{
    protected $value = 1;

    public function setValue($value)
    {
        $this->value = $value;
    }

    public function &getValue()
    {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue();
$obj->setValue(2);
echo $myValue;
?>