CHAPTER 9 ■ GENERATING OBJECTS
class NastyBoss {
private $employees = array();
function addEmployee( $employeeName ) {
$this->employees[] = new Minion( $employeeName );
}
function projectFails() {
if ( count( $this->employees ) > 0 ) {
$emp = array_pop( $this->employees );
$emp->fire();
}
}
}
$boss = new NastyBoss();
$boss->addEmployee( "harry" );
$boss->addEmployee( "bob" );
$boss->addEmployee( "mary" );
$boss->projectFails();
// output:
// mary: I'll clear my desk
As you can see, I define an abstract base class: Employee, with a downtrodden implementation:
Minion. Given a name string, the NastyBoss::addEmployee() method instantiates a new Minion object.
Whenever a NastyBoss object runs into trouble (via the NastyBoss::projectFails() method), it looks for
a Minion to fire.
By instantiating a Minion object directly in the NastyBoss class, we limit flexibility. If a NastyBoss
object could work with any instance of the Employee type, we could make our code amenable to variation
at runtime as we add more Employee specializations. You should find the polymorphism in Figure 9-1
familiar.
Figure 9-1. Working with an abstract type enables polymorphism.