Composition vs Aggregation

Updated: 05 August 2023

An example with PHP:

/* COMPOSITION */
/* If human object is deleted heart object is deleted also. */
class Heart{}

class Human{
    private $heart;
    public function addHeart(){
        $this->heart = new Heart();
    }
}

$human = new Human();
$human->addHeart();

/* AGGREGATION */
/* If car object is deleted engine object still exists. */
class Engine{}

/* The Aggregate */
class Car{
    private $engine;
    public function __construct(Engine $engine){
        $this->engine = $engine;
    }
}

$engine = new Engine();
$car = new Car($engine);

...

Leave a comment