物件導向基礎概念-聚合組合

聚合,因為A出現,所以B出現,A消失時B也就消失
專輯Album是由許多首歌所組成的,沒有專輯就沒有歌

class Song
{
    public function __construct()
    {
        echo "It's a song.<br />";
    }
}

class Album
{
    private $song;
    
    public function __construct()
    {
        echo "It's a Album.<br />";
        $this->song = new Song();
    }
}

$album = new Album();

Browser結果
It’s a Album.
It’s a song.

組合,A、B都是獨立的,但A可用B的某些功能,B可用A的某些功能
剪刀Scissors是由刀片Blade和刀柄Shank組合而成,未組合前也都是獨立的物件,也可以組合成其它的物件

class Blade
{
    public function show()
    {
        echo "It's a blade.<br />";
    }
}


class Shank
{
    public function show()
    {
        echo "It's a shank.<br />";
    }
}

class Scissors
{
    protected $blade;
    protected $shank;
    
    public function __construct(Blade $blade,Shank $shank)
    {
        $this->blade = $blade;
        $this->shank = $shank;
    }
    
    public function show()
    {
        echo "It's a Scissors.<br />";
        $this->blade->show();
        $this->shank->show();
    }
}

$part_blade = new Blade();
$part_shank = new Shank();

$scissors = new Scissors($part_blade,$part_shank);
$scissors->show();

Browser結果
It’s a Scissors.
It’s a blade.
It’s a shank.

雖然這樣理解太果斷:
聚合就是在物件A裡產生物件B
組合就是物件A和物件B是獨立的,但物件A接受了物件B的傳入