473,583 Members | 2,751 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Polymorphism in PHP (+ question on casting "up")

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;
}
}
}
}

Jun 2 '08 #1
5 2187
Ronald Raygun wrote:
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?

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===

Jun 2 '08 #2


Jerry Stuckle wrote:
Ronald Raygun wrote:
>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?
Jun 2 '08 #3
Ronald Raygun wrote:
>

Jerry Stuckle wrote:
>Ronald Raygun wrote:
>>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.
js*******@attgl obal.net
=============== ===

Jun 2 '08 #4
<snip>
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?
If you really want to check if the instance if of class/interface B, use
the instanceof operator. But if you already know it is of
class/interface B, you can just call the method.

If you are used to Visual Basic, this may be surprising to you. But an
interface in PHP just says "conforming objects are guaranteed to have
these methods". Interfaces in PHP do not hide or rename methods.
Jun 2 '08 #5
On May 15, 2:51 pm, Dikkie Dik <dik...@nospam. orgwrote:
<snip>
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?

If you really want to check if the instance if of class/interface B, use
the instanceof operator. But if you already know it is of
class/interface B, you can just call the method.

If you are used to Visual Basic, this may be surprising to you. But an
interface in PHP just says "conforming objects are guaranteed to have
these methods". Interfaces in PHP do not hide or rename methods.
To function correctly, the code only requires at least part of the
interface to be present - instanceof will allow the coder to check if
the object is descended from a class which implements what might be a
suitable method / member variable but its really just a matter of
convenience to have common ancestry - even Java allows interfaces to
be declared independently of the classes which implement them. Long
ancestries can be a performance bottleneck in PHP.

Sometimes method_exists() or property_exists () will be a better way to
work out how to interact with an object.

C.
Jun 2 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
2813
by: Mike Meng | last post by:
hi all, I'm a newbie Python programmer with a C++ brain inside. I have a lightweight framework in which I design a base class and expect user to extend. In other part of the framework, I heavily use the instance of this base class (or its children class). How can I ensure the instance IS-A base class instance, since Python is a fully dynamic...
4
2391
by: Leslaw Bieniasz | last post by:
Cracow, 20.09.2004 Hello, I need to implement a library containing a hierarchy of classes together with some binary operations on objects. To fix attention, let me assume that it is a hierarchy of algebraic matrices with the addition operation. Thus, I want to have a virtual base class class Matr;
3
364
by: Student911 | last post by:
Hello, I read that upward casting is always safe but downward casting/ For example: Derived* p=(Derived*) new Base(); casting can cause problems with the memory. Can someone please give me an example that memory problems are caused? I thought that problems will happen during upward casting since if Person has _name and _id and...
2
1241
by: Frazer | last post by:
hi, I am confused when to use (int) and when to use Convert.toint32.. eg here string s= "1"; int j = (int) s; //this gives me an error and i have to use convert.toint32. why is that so and how do i know when to use which. thnx
61
4535
by: Ken Allen | last post by:
I am relatively new to .Net, but have been using VB and C/C++ for years. One of the drawbacks with VB6 and earlier was the difficulty in casting a 'record' to a different 'shape' so one could perform different manipulations on it. For example, I have a complex data structure, which I can represent in a VB6 TYPE declaration, but I cannot...
8
2124
by: Michael | last post by:
Hi, I think my problem deals with class casting and inheritance. I want to deal with various Audio Formats, reading into memory for modification, working with it (done by different classes), and writing the result to disk afterwards. Therefore I have created some classes, e.g. WaveFileIO and AiffFileIO and MP3FileIO and AuFileIO for...
3
1862
by: lorenzon | last post by:
I've run into a problem in some code involving two class hierarchies that I can't figure out: I have an event hierachy topped with an interface, let's say- IEvent, EventA : IEvent, EventB : IEvent And some handlers-
9
2411
by: Naomi | last post by:
I need to make software engineering decision to do with using a derived data type in a container class. So for example, if I have an Edge class, and I want to make a Edge object which contains two NumberVertices instead of Vertices, I can either just use a non- templated Edge class which stores pointers to my NumberVertices and leave it up...
1
1513
by: alireza6485 | last post by:
Hi, can u help me with polymorphism and up-casting please. Bipeds scream birds fly bird bd =new bied; Bipeds bp bp=bd(upcasting)//what does this line do?is it saying that the biped we have is a bird? bp.scream bd.scream bd.fly
0
7896
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8186
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8329
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6583
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5704
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3821
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3847
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2335
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1160
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.