If a parent class offers a constructor, it does execute when the child class is instantiated,
provided that the child class does not also have a constructor. For example,
suppose that the Employee class offers this constructor:
function __construct($name) {
$this->setName($name);
}
Then you instantiate the CEO class and retrieve the name member:
$ceo = new CEO("Dennis");
echo $ceo->getName();
It will yield the following:
My name is Dennis
202 CHAPTER 7 ?– ADVANCED OOP FEATURES
However, if the child class also has a constructor, that constructor will execute
when the child class is instantiated, regardless of whether the parent class also has a
constructor. For example, suppose that in addition to the Employee class containing
the previously described constructor, the CEO class contains this constructor:
function __construct() {
echo "
CEO object created!
";
}
Then you instantiate the CEO class:
$ceo = new CEO("Dennis");
echo $ceo->getName();
This time it will yield the following output because the CEO constructor overrides
the Employee constructor:
CEO object created!
My name is
When it comes time to retrieve the name member, you find that it??™s blank because
the setName() method, which executes in the Employee constructor, never fires. Of
course, you??™re quite likely going to want those parent constructors to also fire. Not to
fear because there is a simple solution.
Pages:
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280