I want to implement next fragment of diagram, using PHP.
See composition example diagram below:
We can implement composition in Java using inner classes.
But there is no analog of "inner class" in PHP. Of course, there are traits. But we can use it in more than one class.
I've implemented composition like this:
class Head {
private static $instance = NULL;
private function __construct(){}
public static function getInstance() {
$traces = debug_backtrace();
if (strcmp($traces[1]['class'], 'Human')) {
echo "<br>Only human has head"; // Exception can be thrown here
return NULL;
}
if (!static::$instance) static::$instance = new self();
return static::$instance;
}
public function __toString() {
return 'Head';
}
}
class Human {
private $head;
public function __construct() {
$this->head = Head::getInstance();
}
public function __toString() {
return 'I have ' . $this->head;
}
}
class Plant {
private $head;
public function __construct() {
$this->head = Head::getInstance();
}
}
$human = new Human();
echo $human;
$superman = new Plant();
Is it right to do so?
Is there better way to implement composition relationship in PHP?