Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This seems possible by using a <a href="http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members" rel="nofollow noreferrer">magic setter function</a> that you define in <code>foo</code>, but comes with a serious caveat. Magic getters and setters <em>fire only when you access an inaccessible property.</em> </p> <p>When operating inside a class, all properties, no matter whether declared private, public or protected, are usually accessible, so the magic getter and setter functions will not fire. There is only one exception: Properties that were declared <code>private</code> in an ancestor class. Those will be hidden (inaccessible) to descendant classes, and the magic functions will fire.</p> <p>This means that you will need to declare <code>bar</code> and <code>baz</code> in <code>foo</code>. It wouldn't work if you would declare them in <code>foobar</code>, because they would become accessible. </p> <p>With this in mind, the following will work as you want:</p> <pre><code>class foo { private $bar = false; private $baz = NULL; public function __set($name, $value) { if ($name == "bar") { if ($value == true) { if ($this-&gt;baz == null) throw new Exception(); } } } } class foobar extends foo { function test() { $this-&gt;bar = "TEST"; } } $foobar = new foobar(); $foobar-&gt;test(); // Will throw an exception </code></pre> <p>If you want to read <code>bar</code> and <code>baz</code> from within <code>foobar</code>, you will also need to define a magic getter function.</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