如果我创建父类的新实例和子类的新实例,我如何直接更改父类中的变量并查看子类中的更改?
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?
答案 0 :(得分:1)
如果您在父级中有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);
}
希望这会有所帮助。