请参见以下组合示例图表: 我们可以使用内部类在Java中实现组合。但在PHP中没有“内部类”的类比。当然,有traits。但我们可以在多个类中使用它。我已经这样实现了组合:
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();
你这样做是正确的吗?
在PHP中实现组合关系是否有更好的方法?