Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Actually, when you calling <code>$property-&gt;foo-&gt;bar</code> and <code>$property</code> class have magic __get method, you can verify only <code>foo</code> property and throw error only for it.</p> <p>But if your <code>foo</code> is also an instance of the same class (or similar class with the same magic <code>__get</code> method) you can also verify <code>bar</code> property and throw the next error.</p> <p>For example:</p> <pre><code>class magicLeaf { protected $data; public function __construct($hashTree) { $this-&gt;data = $hashTree; } // Notice that we returning another instance of the same class with subtree public function __get($k) { if (array_key_exists($k, $this-&gt;data)) { throw new Exception ("Property $name is not defined"); } if (is_array($this-&gt;data[$k])) { // lazy convert arrays to magicLeaf classes $this-&gt;data[$k] = new self($this-&gt;data[$k]); } return $this-&gt;data[$k]; } } </code></pre> <p>And now just example of using it:</p> <pre><code>$property = new magicLeaf(array( 'foo' =&gt; 'root property', 'bar' =&gt; array( 'yo' =&gt; 'Hi!', 'baz' =&gt; array( // dummy ), ), )); $property-&gt;foo; // should contain 'root property' string $property-&gt;bar-&gt;yo; // "Hi!" $property-&gt;bar-&gt;baz-&gt;wut; // should throw an Exception with "Property wut is not defined" </code></pre> <p>So now you can see how to made it almost like you want.</p> <p>Now just modify a little your <code>__construct</code> and magic <code>__get</code> methods and add new param to know where we are at each level:</p> <pre><code>... private $crumbs; public function __construct($hashTree, $crumbs = array()) { $this-&gt;data = $hashTree; $this-&gt;crumbs = $crumbs; } public function __get($k) { if (array_key_exists($k, $this-&gt;data)) { $crumbs = join('-&gt;', $this-&gt;crumbs); throw new Exception ("Property {$crumbs}-&gt;{$name} is not defined"); } if (is_array($this-&gt;data[$k])) { // lazy convert arrays to magicLeaf classes $this-&gt;data[$k] = new self($this-&gt;data[$k], $this-&gt;crumbs + array($k)); } return $this-&gt;data[$k]; } ... </code></pre> <p>I think it should works like you want.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload