|
Posted by Michael Fesser on 07/23/07 02:21
..oO(Sanders Kaufman)
>Michael Fesser wrote:
>>
>> Correct. PHP doesn't do that automatically, except if the child class
>> doesn't have a constructor. Then PHP will call the one from the base
>> class, if it exists. But as soon as your child class uses its own
>> constructor, you have to manually call the parent one. Usually this
>> should be the first action.
>
>Got it - and I wish I'd got it a year ago!
>
>Is that a normal OOP way to do it - done that way in C++ and whatnot -
>or is this unique to PHP?
It works like that in all languages I know and it simply _has_ to work
that way. The programmer has to be able to exactly define if and when a
parent method will be called. Just consider this little example:
class A {
protected $data = NULL;
public function __construct() {
$this->doSomething();
}
private function doSomething() {
// do something with $this->data
}
}
class B extends A {
public function __construct() {
$this->data = 'foo';
parent::__construct();
}
}
Quite simple: A base class with a member variable and a method that
performs some action with that. Since this is done in the constructor,
every child class has to be able to initialize the data before calling
the parent constructor, as you can see in B::__construct(). If PHP would
automatically call the parent constructor, this would be impossible.
Micha
Navigation:
[Reply to this message]
|