考虑从父类中调用子类的场景,子类可以与父类交互吗?

时间:2015-11-11 17:39:45

标签: php 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");

2 个答案:

答案 0 :(得分:1)

您将使用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);
  }
}

请参阅this答案,了解详细信息。

答案 1 :(得分:0)

回到这个问题,这就是我想要处理这篇文章中提出的问题,将父类引用发送给子类: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>"; 

欢迎任何评论!