考虑到从父类内部调用子类的场景,子类是否可以与父类交互


Considering a scenario where child class is called from within parent class, can child class interect with parent class?

我不知道如何解释,但如果类a引用了一个类B,那么类B有可能与类a交互吗?

class A {
    function A($name) {
        $this->name = $name;
    }
    function addB($name) {
        $this->b = new B($name);
    }
}
class B {
    function B($name) {
        $this->name = $name;
        echo $a->name; // should echo $name set on class A
    }
}
$a = new A("x");
$a->addB("y");

您将使用getter来返回变量。

class A {
  private $myPrivateVar;
  function __construct() {
    $this->myPrivateVar = 100;
  }
  // Accessor (AKA getter)
  public function getMyPrivateVar() {
    return $this->myPrivateVar;
  }
  // Mutator (AKA setter)
  public function setMyPrivateVar($newVar) {
    $this->myPrivateVar = $newVar;
  }
}
class B {
  function __construct() {
    $a = new A();
    $thePrivateVarFromA = $a->getMyPrivateVar();
    $newVal = $thePrivateVarFromA * 100;
    $a->setMyPrivateVar($newVal);
  }
}

请参阅此答案以获得良好的细分。

回到这个问题,这就是我如何处理这篇文章中提出的问题,将父类引用发送到子类:new _child($name, $this):

class _parent {
    function _parent($name) {
        $this->name = "I'm $name";
        $this->childs = array();
    }
    function addToName($name) {
        $this->name .= " + father of " . $name;
    }
    function addChild($name) {
        $this->childs[] = new _child($name, $this);
    }
}
class _child {
    function _child($name, $parent) {
        $this->name = "I'm $name";
        $this->brothers = 0;
        $parent->addToName($name);
        foreach ($parent->childs as $child) {
            $child->hasBrother($name);
        }
    }
    function hasBrother($name) {
        $this->name .= " + older brother of $name";
        $this->brothers = 1;
    }
}
$a = new _parent("A");
$a->addChild("B1");
$a->addChild("B2");
$a->addChild("B3");
echo "<pre>"; print_r($a); echo "</pre>"; 

欢迎任何评论!