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?

我有一个核心类作为收集器,两个子类存储在这个核心类的公共变量中: p>

 类Core 
 {
 public $ cache; 
 public $ html; 
 
 public function __construct()
 {
 $ cache = new Cache(); \  n $ html = new Html(); 
} 
} 
 
class Cache 
 {
 public function __construct()
 {
} 
 
公共函数存储($ value)
 {  
 //做某事
} 
} 
 
class Html 
 {
 public $ foo; 
 
 public function __construct()
 {
 $ foo =“bar”; 
 \ global  $ core; 
 $ core-> cache-> store($ foo); 
} 
 
} 
   code>  pre> 
 
 

问题: 我会 喜欢摆脱“全球$ core”这一行并执行以下操作: $ this-> parent-> cache-> store($ foo) $ cache应以某种方式连接到$ core 因为它是$ core的公共成员 p>

我知道$ html是一个存储为变量而不是继承的子类。 任何想法? p> div>

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.

What you can do is to use the concept of dependency injection to inject in your HTML class an object of the class Cache, and then, use it to call method store. I believe that this is a very good approach. So you can do something like this.

class Core
{
  public $cache;
  public $html;

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

In your class HTML:

    class Html
    {
      public $foo;

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

About your second question, if there is no necessity of do something in the constructor, you could just ommit it. But there is no problem to let it empty as well. So I think that it up to you.