简体   繁体   中英

2 New Instances of a Parent and Child class, need to change Parent variable directly in parent and view in child

PHP

If I create a new instance of a parent class and a new instance of a child class, how can I change the variable in the parent class directly and view the change in the child class?

Take the following code:

class parentClass {

    public $varA = 'dojo';

    public function setVarA() {
        $this->varA = 'something grand';
    }

    public function getVarA() {
        return $this->varA;
    }

}

class childClass extends parentClass {

    public function useVarA() {
        echo parent::getVarA();
    }

}

$parentInstance = new parentClass();
$childInstance = new childClass();

$initialVarA = $parentInstance->getVarA(); // should set $initialVarA variable to 'dojo'

$childInstance->useVarA(); // should echo 'dojo'

$parentInstance->setVarA(); // should set $varA to 'something grand'

$changedVarA = $parentInstance->getVarA(); // should set $changedVarA variable to 'something grand'

$childInstance->useVarA(); // should echo 'something grand' but fails to do so...how can I do this?

If you have either a private or a protected variable (member) in the parent then you can access it simply like this from you child class:

$this->varA = ‘something’;

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 static .

You don't need to declare it public .

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->varA;
    }

    public function getB() {
        return $this->varB;
    }

    public function getC() {
        return $this->varC;
    }

 }

 $child = new Child();

 $child->getA(); // Will not work since $varA is private to Parent
 $child->getB(); // Works fine because $varB is accessible by Parent and subclasses
 $child->getC(); // Works fine but ...
 $child->varC;   // .. will also work.
 $child->getD(); // Will work and reflect any changes to the parent or child.

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.

$parent->addChild(new Child());

And in the set method:

$this->varA = $value;
foreach ($this->children as $child) {
     $child->setVarA($value);
}

Hopes this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM