|
Posted by Dikkie Dik on 08/16/06 22:09
....
> And a child that looks like this:
> Class Status extends State {
> public function __construct($database,$user,$output) {
> parent::__construct($database,$user,$output);
> }
> }
>
>
> This seems to work OK. But I'm getting confused when thinking about
> adding a new child who then has to contruct the parent again. Isn't
> this getting away from the whole purpose of inheritence? It seems like
> this is recreating the parent with every new child that come along.
> Would it be possible to just have a single instance of the parent that
> all children extended or am I missing the point here?
You are not constructing the parent as a separate object. There is only
one object that is specifically the child and more generally the parent
(because the child is a specialization of the parent). However, the
parent may need some data to be constructed with, even if it is
abstract. Calling the parent's constructor from the child does just
that: initialize the code in the parent class. Mind you, due to
inheritance, that code is now active in the child object.
An example:
class Exception
{private internalmessage;
public function __construct(message)
{this->internalmessage = message;}
public function getMessage()
{return this->internalmessage;}
}
class LoginException extends Exception
{public function __construct(message)
{parent::__construct('Could not verify credentials.');}
}
An exception always has to have a message, so it enforces one by
requiring it in the constructor's parameters. This message is kept
safely inside, so it is effectively read-only. Not even a subclass can
touch it.
The subclass LoginException sets an appropriate message by calling its
parent's constructor (that is not done automatically by PHP). But as the
internalmessage in the superclass is private, it is not within reach of
the subclass. Off course, an instance of LoginException will have this
variable somewhere in memory, but only the methods defined in the
superclass can touch it. So there is just one instance then: that of the
child.
Best regards
Navigation:
[Reply to this message]
|