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?
CacheandHtmlclasses are not subclasses of classCore. If you keep instances of them intoCore::$cacheandCore::$htmlthey are collaborators. But inCore::__construct()you create two instances ofCacheandHtmland "keep" them in local variables that vanish when the function completes. Read more about PHP Classes and Objects and variables scope$this->cacheand$this->htmlas suggested in the accepted answer) is "composition". A "collaborator" is an object passed as argument to a method call; the method delegates some work to the collaborator by calling one (or many) of its methods. It can be saved in a property for subsequent usage but this is not a requirement.