php object design parent child

141 views Asked by At

I would like to use parent/child classes in php, but not in the way of subclasses. As an example, let's say we have a class House and a house has Doors and Windows.

class House {
}

class Door {
}

class Window {    
}

And we have two types of doors, let's say the garage door and the front door.

class GarageDoor extends Door {
}

class FrontDoor extends Door {
}

How can I create the relationship between House and Door and between House and Window such that when I create a door, there must be at least a house and I should know the specific house. And when I delete a house, also its doors and windows should be deleted. How can I do that?

1

There are 1 answers

3
martindilling On BEST ANSWER

Not saying it's the best or even a good way to go about it, but it should give you something to play around with and trying yourself to experiment with different things :)

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);