dp7311 2017-03-21 11:20
浏览 38
已采纳

php访问子类的父对象(无继承)

I have a core class as a collector and two subclasses stored in public variables in this core class:

class Core
{
  public $cache;
  public $html;

  public function __construct()
  {
    $cache = new Cache();
    $html  = new Html();
  }
}

class Cache
{
  public function __construct()
  {
  }

  public function store($value)
  {
    // do something
  }
}

class Html
{
  public $foo;

  public function __construct()
  {
    $foo = "bar";
    global $core;
    $core->cache->store($foo);
  }

}

QUESTION: I would like to get rid of the line "global $core" and do something like: $this->parent->cache->store($foo) $cache should be connected to $core in some way because it is a public member of $core

I know that $html is a subclass stored as a variable and not an inheritance. Any ideas?

Second question: Can I leave out the empty constructor in the Cache-Class?

  • 写回答

2条回答 默认 最新

  • du512926 2017-03-21 11:31
    关注

    Your object can't access caller class methods, because he do not know anything about it's caller.

    You can try to pass parent when creating new object

    class Core {
       public $cache;
       public $html;
    
       public function __construct() {
           $this->cache = new Cache($this);
           $this->html = new Html($this);
       }
    }
    
    class Html {
        public $parent;
    
        public function __construct($parent) {
            $this->parent = $parent;
    
            if (!empty($this->parent->cache)) {
                $this->parent->cache->store();
            }
        }
    }
    

    Can I leave out the empty constructor - yes, you even do not have to declare __construct method at all, as all classes has it's default constructor/destructor.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用