Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you have either a <code>private</code> or a <code>protected</code> variable (member) in the parent then you can access it simply like this from you child class:</p> <pre><code>$this-&gt;varA = ‘something’; </code></pre> <p>There reason why your child method does not reflect the change, is that child and parent are two different objects in separate memory space. If you want them to share a value you could make it <code>static</code>.</p> <p>You don’t need to declare it <code>public</code>.</p> <pre><code>class Parent { private $varA; protected $varB; public $varC; protected static $varD; public function getD() { return self::$varD; } public function setD($value) { self::$varD = $value; } } class Child extends Parent { public function getA() { return $this-&gt;varA; } public function getB() { return $this-&gt;varB; } public function getC() { return $this-&gt;varC; } } $child = new Child(); $child-&gt;getA(); // Will not work since $varA is private to Parent $child-&gt;getB(); // Works fine because $varB is accessible by Parent and subclasses $child-&gt;getC(); // Works fine but ... $child-&gt;varC; // .. will also work. $child-&gt;getD(); // Will work and reflect any changes to the parent or child. </code></pre> <p>If you don’t want all instance of the parent class to share values. You could pass on the parent or child to either new instance and through and update the values of all the related objects accordingly.</p> <pre><code>$parent-&gt;addChild(new Child()); </code></pre> <p>And in the set method:</p> <pre><code>$this-&gt;varA = $value; foreach ($this-&gt;children as $child) { $child-&gt;setVarA($value); } </code></pre> <p>Hopes this helps.</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