php对象设计父子

时间:2016-12-21 16:57:07

标签: php class oop extends

我想在php中使用父/子类,但不是以子类的方式。举个例子,假设我们有一个House House,一个房子有门和Windows。

/layout

我们有两种类型的门,比如车库门和前门。

class House {
}

class Door {
}

class Window {    
}

我如何创建House和Door之间以及House和Window之间的关系,这样当我创建一扇门时,必须至少有一所房子,我应该知道具体的房屋。当我删除一个房子时,也应该删除它的门窗。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

不是说它是最好的,甚至是一种很好的方式,但它应该给你一些东西可以玩,并尝试自己尝试不同的东西:)

class House 
{
    /**
     * An array of all doors that have been installed in the house.
     */
    private $doors = [];

    /**
     * You can install a door in a house.
     */
    public function installDoor(Door $door)
    {
        $this->doors[] = $door;
    }
}

class Door
{
    /**
     * A reference to the house this door is installed in.
     */
    private $house = null;

    /**
     * A house is required before a door can be created.
     */
    public function __construct(House $house)
    {
        $house->installDoor($this);
        $this->house = $house;
    }
}

$house = new House();
$door = new Door($house);