小编pro*_*ort的帖子

如何在php中实现组合

我想使用PHP实现图的下一个片段.

请参阅下面的组成示例图:

在此输入图像描述

我们可以使用内部类在Java中实现组合.

但PHP中没有"内部类"的类比.当然,还有一些特点.但是我们可以在多个班级中使用它.

我已经实现了这样的组合:

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 …
Run Code Online (Sandbox Code Playgroud)

php oop composition

9
推荐指数
2
解决办法
9107
查看次数

标签 统计

composition ×1

oop ×1

php ×1