CHAPTER 9 ■ GENERATING OBJECTS
object state when you generate new products. Imagine that Sea objects have a $navigability property.
The property influences the amount of movement energy a sea tile saps from a vessel and can be set to
adjust the difficulty level of a game:
class Sea {
private $navigability = 0;
function __construct( $navigability ) {
$this->navigability = $navigability;
}
}
Now, when I initialize the TerrainFactory object, I can add a Sea object with a navigability modifier.
This will then hold true for all Sea objects served by TerrainFactory:
$factory = new TerrainFactory( new EarthSea( -1 ),
new EarthPlains(),
new EarthForest() );
This flexibility is also apparent when the object you wish to generate is composed of other objects.
Perhaps all Sea objects can contain Resource objects (FishResource, OilResource, etc.). According to a
preference flag, we might give all Sea objects a FishResource by default. Remember that if your products
reference other objects, you should implement a __clone() method in order to ensure that you make a
deep copy.
■Note I covered object cloning in Chapter 4. The clone keyword generates a shallow copy of any object to
which it is applied. This means that the product object will have the same properties as the source. If any of the
source’s properties are objects, then these will not be copied into the product. Instead, the product will reference
the same object properties. It is up to you to change this default and to customize object copying in any other way,
by implementing a __clone() method. This is called automatically when the clone keyword is used.
class Contained { }
class Container {
public $contained;
function __construct() {
$this->contained = new Contained();
}
function __clone() {
// Ensure that cloned object holds a
// clone of self::$contained and not
// a reference to it
$this->contained = clone $this->contained;
}
}