简体   繁体   English

php oop遍历parent :: child关系

[英]php oop traversing the parent::child relationship

my actual code is complex so here is a simple but relevant illustration: 我的实际代码很复杂,因此这里有一个简单但相关的示例:

class base {

  var $child1;
  var $child2;

  function xcv() {
    $this->child1 = new objChild1();
    $this->child2 = new objChild2();
  }
}

class objChild1 {
  var $fruit = "apple";
}

class objChild2 {
  function getChild1Fruit() {
    echo parent::child1->fruit;
  }
}

fairly straight forward but what if objGrandchild1 wants to call child2 etc... is it like parent::parent::child1->fruit? 相当简单,但是如果objGrandchild1想调用child2等呢?是像parent :: parent :: child1-> fruit?

any tips in this area would be appreciated 这方面的任何技巧将不胜感激

===== EDIT ===== Sorry I just realised that parent belongs to the use of extend so probably nothing to do with it =====编辑=====对不起,我刚刚意识到父级属于extend的使用,因此可能与其无关

You got it right in the edit you made. 您在所做的编辑中完全正确。 An object has no realisation of the object that's being used in. You could get this reference through a parameter, though. 对象没有实现正在使用的对象。不过,您可以通过参数获取此引用。

class base {

  var $child1;
  var $child2;

  function xcv() {
    $this->child1 = new objChild1();
    $this->child2 = new objChild2($this);
  }
}

class objChild1 {
  var $fruit = "apple";
}

class objChild2 {
  objChild2($parent) {
    $this->parent = $parent;
  }
  function getChild1Fruit() {
    echo $this->parent->child1->fruit;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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