Robert
Robert

Reputation: 19

php access parent object of a subclass (no inheritance)

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?

Upvotes: 0

Views: 213

Answers (2)

Wellington Braga
Wellington Braga

Reputation: 65

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.

Upvotes: 1

Justinas
Justinas

Reputation: 43471

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.

Upvotes: 0

Related Questions