Using $this->key with overloaded __get() in PHP
<p>I have a dynamically loading class as a variable within another class. I have implemented it as follows:</p>

<pre><code>public function &amp;__get($key) {
    if (array_key_exists($key, $this-&gt;values) { return $this-&gt;values[$key]; }

    if ($key == "dr") {
        if (!$this-&gt;dr) { $this-&gt;dr = new DR(); }
        return $this-&gt;dr;
    }
}
</code></pre>

<p>When I utilize this function from outside the class it works as expected:</p>

<pre><code>echo $p-&gt;dr-&gt;name;
</code></pre>

<p>Seamlessly creates DR and returns its name. 
When I use the same technique from inside the class the <code>__get()</code> function does not get called, and I receive NULL:</p>

<pre><code>function drname() {
  return $this-&gt;dr-&gt;name;
}
</code></pre>

<p>I think I understand why (otherwise PHP would create infinite loop in my first example), but how do I solve this? I figured out a solution using: <code>$this-&gt;__get('dr')-&gt;name</code> but is this really the best/only way? It seems hacky.</p>
