Ronald Raygun wrote:
Quote:
>
>
Jerry Stuckle wrote:
>
Quote:
>Ronald Raygun wrote:
>>
Quote:
>>If I have the following class heirarchy:
>>>
>>class A{
>> protected $m_type;
>> function type(){return $this->m_type;}
>>}
>>>
>>class B extends A{}
>>class C extends B{}
>>>
>>class D{
>> private A $m_objref ; //reference to object of type A
>> //Is this possible?
>> public function foobar(A $obj){
>> switch($obj->type()){
>> case: 1 //treat as A
>> A $myvar_a = obj;
>> break;
>>>
>> case: 2 //treat as B (do I need an explicit cast here?)
>> B $myvar_b = obj;
>> break;
>>>
>> case: 3 //treat as C (do I need an explicit cast here?)
>> C $myvar_c = obj;
>> break;
>> }
>> }
>> }
>>}
>>>
>>>
>>
>Maybe a better question would be what are you actually trying to do?
>>
>
I have a session class that stores a user. There are different types of
users (with different methods), but they each derive from a base User
class. I want to have one single reference that points to the user object.
>
The case I make above helps to find out what the PHP language limits are
(not to mention "gotchas", if I make C++ like assumptions in my code).
>
On a more practical level, on pages where a user (of type B for example)
is expected, (after preliminary sanity checks), I will need to start
treating the variable as a variable of Type B, although it is stored as
a reference to a User (remember Class B is-a 'User'). This is where my
question about "casting down[corrected]" (the class diagram) comes in.
>
Can I simple sstart calling methods on the 'B' interface, or do I need
to make an explicit cast from 'User' to 'B', before using the object
retrieved from the session?
>
OK, no casting is needed in PHP. But IMHO this isn't a good OO design.
If you're going to be calling methods depending on the type, those
methods should be defined in the base class with a default response and
overridden as necessary in the derived classes.
The same is true in C++, BTW. Down casting is highly frowned upon. It
creates too many dependencies in the code and makes the code difficult
to maintain. Things OO was designed to make better.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================