PHP Return by Reference Clarification
<p>I have an example script here with a return by reference magic __get:</p>

<pre><code>class a{

    public $_attributes = array();

    function &amp;__get($k){
        if(isset($this-&gt;_attributes[$k])){
            return $this-&gt;_attributes[$k];
        }else{
            return null;
        }
    }

    function __set($k, $v){
        $this-&gt;_attributes[$k] = $v;
    }
}


$a = new a();
$a-&gt;username = "sam";
var_dump($a-&gt;username);
$u = $a-&gt;username;
$u = $u.'dddd';
var_dump($a-&gt;username);
var_dump($u);
</code></pre>

<p>The idea of returning by reference from my __get here is so I can do stuff like:</p>

<pre><code>    $this-&gt;user-&gt;ins[session_id()] = array(
        "key"=&gt;$_SESSION['server_key'],
        "ip"=&gt;$_SERVER['REMOTE_ADDR'],
        "agent"=&gt;$_SERVER['HTTP_USER_AGENT'],
        "last_request"=&gt;$_SERVER['REQUEST_URI'],
        "last_active"=&gt;new MongoDate(),
    );
</code></pre>

<p>Since I cannot normally due to PHP using a copy of the original array. However When I pull say "username" into a new variable ($u) I do not want it to pass a reference of its original parent.</p>

<p>The script above prints out:</p>

<pre><code>string(3) "sam" string(3) "sam" string(7) "samdddd"
</code></pre>

<p>Which is awesome becasue it is not passing $username as reference back to $u and it works like I want it to. </p>

<p>Now time for the question: Is this a good approach? Is it expected behaviour in PHP to do this?</p>

<p>I have been reading the page for referencing but it's a bit patchy, however it does mention that to tell PHP that $u should be a reference I must also use the reference symbol when pulling out the variable (as can be seen here: <a href="http://php.net/manual/en/language.references.return.php" rel="nofollow">http://php.net/manual/en/language.references.return.php</a>).</p>

<p>So is this expected behaviour and can I rely on it in PHP or is there something terrible I'm not seeing?</p>

<p>Thanks</p>
