LXXIII. Object Aggregation/Composition
Functions
Warning
This extension is EXPERIMENTAL. The behaviour of this extension
-- including the names of its functions and anything else
documented about this extension -- may change without notice
in a future release of PHP. Use this extension at your own
risk.
Introduction
In Object Oriented Programming, it is common to see the
composition of simple classes (and/or instances) into a
more complex one. This is a flexible strategy for building
complicated objects and object hierarchies and can function
as a dynamic alternative to multiple inheritance. There
are two ways to perform class (and/or object) composition
depending on the relationship between the composed elements:
Association and Aggregation.
An Association is a composition of independently constructed
and externally visible parts. When we associate classes
or objects, each one keeps a reference to the ones it is
associated with. When we associate classes statically, one
class will contain a reference to an instance of the other
class. For example: Example 1. Class association
<?php
class DateTime {
function DateTime()
{
// empty constructor
}
function now()
{
return date("Y-m-d H:i:s");
}
}
class Report {
var $_dt;
// more properties ...
function Report()
{
$this->_dt = new DateTime();
// initialization code ...
}
function generateReport()
{
$dateTime = $_dt->now();
// more code ...
}
// more methods ...
}
$rep = new Report();
?>
We can also associate instances at runtime by passing a
reference in a constructor (or any other method), which
allow us to dynamically change the association relationship
between objects. We will modify the example above to illustrate
this point:
|