Page 1 of 1

Psuedo-polymorphism

Posted: Sun Jun 05, 2005 7:23 pm
by MathewByrne
Hi,

I've got a small problem I want to sovle in PHP4 using classes to sort of emulate polymorphism. I've got several similar classes which all have a display() function in them. What I want to do is create an array of these objects and be able to loop through each of them calling the display() function. Is it possible to do something like this?

Code: Select all

$ob1 = new Object1();
$ob2 = new Object2();
$ob3 = new Object3();

$object_array = array($ob1, $ob2, $ob3);

for($i = 0; $i < count($object_array); $i++)
   $object_array[$i]->display();
I know this is possible via interfaces and such in PHP5 but can this be done in PHP4?
Edit: Sorry I know it's the wrong forum! :oops: I meant to stick this in Code

Posted: Sun Jun 05, 2005 7:44 pm
by neophyte
If the object just contains a list of variables and values you can cast the object as an array and then loop through it.

Code: Select all

$object_array = (array) $object ;
In php you don't have to implicitly define an object. You can do something like:

Code: Select all

$object -> username = 'dead';
That is legal. Some people who hate the array syntax use casting and data objects like the above. Although it isn't very common.

Check out the type juggling manual:

http://us2.php.net/language.types.type-juggling

Posted: Sun Jun 05, 2005 7:58 pm
by MathewByrne
Hmm, not sure if I understand your reply in relation to my question. I don't neccesarily want to extract any information from the objects themselves. What I want to do is create an array of 3 different objects which all have the same function (display()) in them. Then I want to loop through all the objects and call display().

Posted: Sun Jun 05, 2005 8:23 pm
by neophyte
:lol: :lol: Missed the boat on that one.

Posted: Sun Jun 05, 2005 10:32 pm
by andre_c
Actually that should work just the way you wrote it, are you getting errors?
(and you don't need interfaces to have it work on php5 either)

Posted: Mon Jun 06, 2005 2:55 am
by MathewByrne
Haha, it does work :D. On a side note for anyone else reading this it might just be easier to do:

Code: Select all

foreach($objectArray as $object)
   $object->display();
And in reguard to PHP5 and interfaces I was more talking about the traditional OOP approach rather than what is and isn't possible in PHP.