puiu91
9/29/2015 - 3:19 PM

composition-and-aggregation.php

<?php

/**
 * Existence of Composition class requires that an external object of 
 * class B is passed in on construction
 * 
 * UML Explanation - The object at this role contains the object at the opposite role. 
 * 
 * Alternatively stated, an object of class Composition cannot be created without 
 * an object of class B (in this case through dependency injection)
 */
class Composition {
    private $internal_obj;
    
    public function __construct(B $external_obj) {
        $this->internal_obj = $external_obj; // requires an object of class B
    }
}

/**
 * Existence of the Aggregation class does not require the existence of B class, 
 * since the Aggregation class builds its own object of class B
 * 
 * UML Explanation - Object at this role contains references to the object at the other role
 */
class Aggregation {
    private $internal_obj;
    
    public function __construct() {
        $this->internal_obj = new B;
    }
}