Hi,
I'm making this request for help because my experience with object
oriented programming is very limited. I'd like to describe my situation
and then ask a question at the end of it, any comments or input are very
appreciated.
My application needs to keep track of different kinds of projects, and
display different attributes depending on what kind of project it is.
Therefore, I have written a base class called Project.
The four kinds of projects are PrintProjects, DesignProjects,
WebProjects, and PhotoProjects. Each of these extend the Project class,
so they are child classes. I intend to write my code to use
polymorphism so that a single method call, $object->display(), will
generate the appropriate output depending on which child class it is
being called upon. So really, the Project class is just an abstract
class and is not really intended to be instantiated, but PHP doesn't
really enforce a difference between abstract classes and true classes.
And each project has a corresponding record in a MySQL database, so I
have a convenient primary key for every Project object (regardless of
what kind of project it is).
HOWEVER --
Because this is PHP/HTTP and not Java, there is no true "state". So the
way that I instantiate a Project is by passing the primary key of the
object as an argument to the constructor of the Project. The
constructor can then "flesh out" the object as needed, and ideally there
will be different "flesh out" code depending on the type of object. My
problem is that I have no way to know which type of object to
instantiate in advance -- all I have is this primary key. Using the
primary key to instantiate an object, I can extract the ProjectType
primary key, and then I could instantiate a new object of the
appropriate type, but then I'd have two objects (and that seems like a
lot of overhead). I'd rather just have the client code instantiate the
right type of object from the beginning.
Is there a way to convert a Project object into a PrintProject object --
such as casting it? In other words, I'd like my client code to look
like:
$obj = new Project('87633');
$type = $obj->getProjectType();
if ($type == '1') {
$obj = (PrintProject)$obj; // re-cast the Project into a PrintProject
} elseif ($type == '2') {
$obj = (DesignProject)$obj; // re-cast the Project into a DesignProject
// etc
}
$obj->display(); // now the object will call the appropriate
// overriding method because the object is
// now of the appropriate subtype
Is that possible in PHP ???? Namely, the casting above?
Or does my client code need to be able to figure out which type of
project it is (say, from the DB) and then use this to determine which
object type to instantiate?
Thanks very much,
Erik
----
Erik Price
Web Developer Temp
Media Lab, H.H. Brown
[EMAIL PROTECTED]
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php