2个父级和子级类的新实例,需要直接在父级中更改父级变量,并在子级中查看

问题描述

| 的PHP 如果创建父类的新实例和子类的新实例,如何直接在父类中更改变量并查看子类中的更改? 采取以下代码
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?
    

解决方法

        如果父级中有
private
protected
变量(成员),则可以从子类中像下面这样简单地访问它:
$this->varA = ‘something’;
您的子方法无法反映更改的原因是,子方法和父方法是单独的内存空间中的两个不同的对象。如果您希望他们分享价值,可以将其设为
static
。 您无需声明
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.
如果您不希望父类的所有实例共享值。您可以将父项或子项传递给新实例,然后传递并相应地更新所有相关对象的值。
$parent->addChild(new Child());
并在set方法中:
$this->varA = $value;
foreach ($this->children as $child) {
     $child->setVarA($value);
}
希望这会有所帮助。