Example 2. Object association
<?php
class DateTime {
// same as previous example
}
class DateTimePlus {
var $_format;
function DateTimePlus($format="Y-m-d H:i:s")
{
$this->_format = $format;
}
function now()
{
return date($this->_format);
}
}
class Report {
var $_dt; // we'll keep the reference to DateTime here
// more properties ...
function Report()
{
// do some initialization
}
function setDateTime(&$dt)
{
$this->_dt =& $dt;
}
function generateReport()
{
$dateTime = $this->_dt->now();
// more code ...
}
// more methods ...
}
$rep = new Report();
$dt = new DateTime();
$dtp = new DateTimePlus("l, F j, Y (h:i:s a, T)");
// generate report with simple date for web display
$rep->setDateTime(&$dt);
echo $rep->generateReport();
// later on in the code ...
// generate report with fancy date
$rep->setDateTime(&$dtp);
$output = $rep->generateReport();
// save $output in database
// ... etc ...
?>
Aggregation, on the other hand, implies encapsulation (hidding)
of the parts of the composition. We can aggregate classes
by using a (static) inner class (PHP does not yet support
inner classes), in this case the aggregated class definition
is not accessible, except through the class that contains
it. The aggregation of instances (object aggregation) involves
the dynamic creation of subobjects inside an object, in
the process, expanding the properties and methods of that
object.
Object aggregation is a natural way of representing a whole-part
relationship, (for example, molecules are aggregates of
atoms), or can be used to obtain an effect equivalent to
multiple inheritance, without having to permanently bind
a subclass to two or more parent classes and their interfaces.
In fact object aggregation can be more flexible, in which
we can select what methods or properties to "inherit"
in the aggregated object.