downcasting in php

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

An API function gives me an object of class 'Blah'. I have subclassed
'Blah' and added a few methods:

   class EnhancedBlah extends Blah {
       function enhancement1() {}
       function enhancement2() {}

Is there a way to 'downcast' the object to a subclass? Something like

   $blah = SuperApi::getBlah();
   $enhancedBlah = (EnhancedBlah) $blah;

Thanks for your help.


Re: downcasting in php

Quoted text here. Click to load it

No. That would break the substitution principle. It is the other way
around. You can create an instance of the subclass and treat it like you
would treat an instance of the superclass. Subclasses are more detailed
than superclasses, so you would need extra info when downcasting. In
fact, superclasses are usually generic terms, and therefore abstract
(non-technical meaning here), even if they don't have abstract methods
in the technical sense.

An everyday example:
The superclass "policeman" has subclasses "inspector", "traffic
policeman", etc. The common functionality gets in the superclass. "make
arrest", for example. You can ask any member of a specific subclass to
perform his duty as a member of the superclass. But not the other way
around. In fact, there is no such thing as a "policeman" instance: every
policeman is a specific member of a subclass of "policeman".

Best regards.
Willem Bogaerts

Application smith
Kratz B.V.

Re: downcasting in php

At Thu, 24 May 2007 23:07:18 -0700, Ryan van Roode let his monkeys type:

Quoted text here. Click to load it

Nope. Simple reason: Every cat (ExtendedBlah) is a mammal (Blah), not
every mammal (Blah) a cat (ExtendedBlah).  
So you can treat Enhancedblah as a Blah, but not the other way around.


Re: downcasting in php

On 25.05.2007 08:07 Ryan van Roode wrote:
Quoted text here. Click to load it

Technically that's possible, see e.g.

but as others already said, the very idea is wrong.

gosha bine

extended php parser ~
blok ~

Re: downcasting in php

At Fri, 25 May 2007 10:18:48 +0200, gosha bine let his monkeys type:

Quoted text here. Click to load it

The effect may be comparable to a sort of cast, but it isn't. It's simply
(ab)using the serialize function to copy just the vars/values and not the
methods of another class.  

If OP has a need to do such a thing he probably should loook at his class
design compared to what he was trying to achieve at a more abstract level.
Good chance his original design is flawed.


Re: downcasting in php

The trick I usually use if I need to do something similar to that is
to create a constructor for the subclass that takes the parent class
as its only parameter. Then you just do

$obj = new Blah();
$obj = new EnhancedBlah($obj);

Same type of effect and you can still use the $obj anywhere you have
before because its a subclass now.

Quoted text here. Click to load it

Site Timeline