Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: Limiting static variable scope to specific class
    text
    copied!<pre><code>abstract class Mother { protected static $foo = null; protected static $bar = null; public function getFoo() { return static::$foo; } public function getBar() { return static::$bar; } public function setFoo($foo) { static::$foo = $foo; } public function setBar($bar) { static::$bar = $bar; } } class Brother extends Mother { protected static $foo = 'BROTHERS'; } class Sister extends Mother { protected static $foo = 'SISTERS'; } $brother1 = new Brother(); $brother2 = new Brother(); $sister1 = new Sister(); $sister2 = new Sister(); $sister1-&gt;setBar('ONLY SISTERS'); // We set $bar = 'ONLY SISTERS' at sister1. // We want only Sister instances to get this value... // however Brother instances also get this value! echo '&lt;p&gt;Brother 1: Foo="'.$brother1-&gt;getFoo().'", Bar="'.$brother1-&gt;getBar().'"&lt;/p&gt;'; // Foo="BROTHERS", Bar="ONLY SISTERS" echo '&lt;p&gt;Brother 2: Foo="'.$brother2-&gt;getFoo().'", Bar="'.$brother2-&gt;getBar().'"&lt;/p&gt;'; // Foo="BROTHERS", Bar="ONLY SISTERS" echo '&lt;p&gt;Sister 1: Foo="'.$sister1-&gt;getFoo().'", Bar="'.$sister1-&gt;getBar().'"&lt;/p&gt;'; // Foo="SISTERS", Bar="ONLY SISTERS" echo '&lt;p&gt;Sister 2: Foo="'.$sister2-&gt;getFoo().'", Bar="'.$sister2-&gt;getBar().'"&lt;/p&gt;'; // Foo="SISTERS", Bar="ONLY SISTERS" </code></pre> <p>So apparently if static::$bar is not explicitly redefined in every child (Brother, Sister) their parent (Mother) will set the value for them (or at least for those who did not redefine it).</p> <p><strong>The question</strong>: Is there any way to prevent children who did not redefine static::$bar from receiving the new value? In other words, how to make sure only the referred class gets a new value, EVEN if static::$bar is not explicitly redefined in every child?</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