Let's test the code
In order to implement the code, we need to:
- First, create an object from one of the basic classes (in our example, it is the Suv class).
- Pass the object that was created from the basic class as a parameter to the class that adds the first feature (i.e., the SunRoof class).
- Pass the object that was created from the first feature class to the second feature class, and so on until we finish adding all the optional features.
- Run the methods on the last object that we created in the process of decoration.
The code below equips the basic Suv with a SunRoof.
// Create an object from one of the basic classes.
$basicCar = new Suv();
// Pass the object from the basic class as a parameter to the first feature class.
$carWithSunRoof = new SunRoof($basicCar);
Once we finish adding the features to the basic class, we are able to run the cost and description methods to give us the details of the
Suv with a sunroof object that we have just created.
// Run the methods on the last object that was created.
echo $carWithSunRoof -> description();
echo " costs ";
echo $carWithSunRoof -> cost();
Result:
Suv, sunroof costs 31500
Another example involves Suv that we'd like to equip with both a sunroof as well as high end wheels.
// 1. Create an object from one of the basic classes.
$basicCar = new Suv();
// 2. Pass the object from the basic class as a parameter to the first feature class.
$carWithSunRoof = new SunRoof($basicCar);
// 3. Pass the object from the first feature class as a parameter to the second feature class.
$carWithSunRoofAndHighEndWheels = new HighEndWheels($carWithSunRoof);
// 4. Run the methods on the last object that was created.
echo $carWithSunRoofAndHighEndWheels -> description();
echo " costs ";
echo $carWithSunRoofAndHighEndWheels -> cost();
And the result:
Suv, sunroof, high end wheels costs 33500