Polymorphism

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Just to further highlight what my understanding of polymorphism is - and that it's not "it can't involve OOP":

Code: Select all

class Controller {
    function run () {
        $model =& $this->selectModel();
        $this->view->run($model);
    }

    /* this is the polymorphic 'section' */
    function & selectModel () {
        if (strpos(PHPOS, 'Win') !== false)) {
            return new WindowsModel();
        } else {
            return new UnixModel();
        }
    }
}
i.e. it's only for the ability to autonomously make a decision based upon the provided parameters or environment. It can be anything - which TimeZone to use in a simple arithmetic time calculation, right up to something like deciding if the application should display HTML/XML/Plaintext based upon the user agent (i.e. decide which view to use.)
abalfazl
Forum Commoner
Posts: 71
Joined: Mon Sep 05, 2005 10:05 pm

Post by abalfazl »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hello!

Code: Select all

interface Animal 
{ 
       // This is the interface all animals have to conform to
       public function setName($name);
       public function makeSound();
} 

class Cat implements Animal 
{ 
        var $name;
        function makeSound() 
        { 
               // Here we override makeSound() 
               echo "Meow!\n"; 
        } 
        function setName($name)
        {
                $this->name = name;
        }
} 

class Dog implements Animal 
{ 
       var $name;
       function makeSound() 
       { 
               echo "Woof!\n"; 
       } 
       function setName($name)
       {
                $this->name = name;
        }

} 

class Squirrel implements Animal 
{ 
       var $name;
       function makeSound() 
       { 
               echo "...\n"; 
       } 
       function setName($name)
       {
                $this->name = name;
       }
       // Note that setName() is the same in all classes
       // Inheritance prevents this kind of code duplication, interfaces don't.
} 

// $a = new Animal; We can't do this any more
$c = new Cat; 
$d = new Dog; 
$s = new Squirrel; 

$c->makeSound(); // Outputs "Meow!" 
$d->makeSound(); // Outputs "Woof!" 
$s->makeSound(); // Outputs "..." 

$animals = array($c, $s, $d); 
foreach($animals as $animal) 
{ 
       $animal->makeSound(); // Outputs "Meow!", "..." and "Woof!"
}

Is it god polymorphism?


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

The foreach part of it is an example of polymorphism. I wouldn't necessarily call it "good polymorphism." That would imply that "bad polymorphism" existed. I'm pretty sure that is exactly why PHP added the interface in version 5 (even though they automagically did it anyway... cool word :lol:).
sike
Forum Commoner
Posts: 84
Joined: Wed Aug 02, 2006 8:33 am

Post by sike »

Jenk wrote:Just to further highlight what my understanding of polymorphism is - and that it's not "it can't involve OOP":

Code: Select all

class Controller {
    function run () {
        $model =& $this->selectModel();
        $this->view->run($model);
    }

    /* this is the polymorphic 'section' */
    function & selectModel () {
        if (strpos(PHPOS, 'Win') !== false)) {
            return new WindowsModel();
        } else {
            return new UnixModel();
        }
    }
}
i.e. it's only for the ability to autonomously make a decision based upon the provided parameters or environment. It can be anything - which TimeZone to use in a simple arithmetic time calculation, right up to something like deciding if the application should display HTML/XML/Plaintext based upon the user agent (i.e. decide which view to use.)
you have a very uncommon slant on what polymorphism is :)
polymorphism is more of a decision "enabler" than something that makes decisions.

chris
abalfazl
Forum Commoner
Posts: 71
Joined: Mon Sep 05, 2005 10:05 pm

Post by abalfazl »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hello!
http://php-mag.net/itr/online_artikel/p ... d,114.html
[quote]

The usage of switch() in an OO situation is hardly ever needed, and even if it is, you might want to reconsider it. Using switch() to determine what to do with an object can become a maintenance nightmare. If you use switch() to determine of which type an object is, after which you are going to do things with the object in every different case, requires that you update your switch() statement every time a new object is added to your application. We do not want that, do we? In case you do not really know what I am ranting about, the bad example is shown in listing 7. Say, we want to build a stack of the form elements explained in the "inheritance" section, loop through them, and based on what exact form element (type) we run into, we want to print the HTML code.

Listing 7

Code: Select all

<?php
// note: make sure the definitions of the form element classes are available here

// instantiate some form elements
$myTextfield = new TextFormElement(
"myTextfield",
"My Textfield",
"a value",
20
);
$myCheckbox = new CheckboxFormElement(
"myCheckbox",
"My Checkbox",
"a value",
true
);
$mySecondCheckbox = new CheckboxFormElement(
"mySecondCheckbox",
"My Second Checkbox",
"a value",
true
);

// make an array of all the elements so we can loop through them
$objects = array($myTextfield, $myCheckbox, $mySecondCheckbox);

foreach ($objects as $object) {
//see of what type the current object is
switch (get_class($object)) {
case "textformelement":
// print html code for current text element here
break;
case "checkboxformelement":
// print html code for current checkbox element here
break;
default:
break;
}
}
?>
[/quote]




What is your idea about using switch for polymorphism?


Another question:What do you think about duck typing?


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
abalfazl
Forum Commoner
Posts: 71
Joined: Mon Sep 05, 2005 10:05 pm

Post by abalfazl »

Hello friends

feyd:
PHP doesn't support overloading, just overriding.

:arrow: http://uk2.php.net/overload

:!: 8O :)

Thanks in advance!

Good Luck!
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

What? Maybe my understand of overload is incorrect, but I've been programming in C++ for years and I've always understood it to be giving multiple functions the same name, and it determines which function is called by the amount of arguments given.

Code: Select all

void CWindow::CreateWindow(int nSize)
{
    // Make the window even height and width
}

void CWindow::CreateWindow(int nWidth, int nHeight)
{
    // Make the window based on width and height parameters
}
In PHP, you can give functions default parameter values, so it's style of doing such is much different.

Code: Select all

public function CreateBox($width, $height = NULL)
{
    if($height === NULL)
    {
        // Make box with even width and height
    }
    else
    {
        // Make box according to width and height parameters
    }
}
Am I not seeing this correctly? PHP's "overloading" doesn't seem to apply to any more than the "magic" functions, and that still seems like just overriding to me.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

There is no overloading in PHP because you aren't allowed to redeclare functions. PHP doesn't use function signatures like other languages, it simply stores the name of the function.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

That's not overloading in the common meaning of this word. Compare with http://en.wikipedia.org/wiki/Method_overloading
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Also, to add to my overloading example, I forgot that overloading is more than just the arguments given, but also the data type. The arguments just made it easier for me to compare it to PHP. It's been so long since I've used data types that I completely forgot until now.


What reminded me was that, today, I got bored and borrowed PHP 5 for Dummies since I'm generally new to PHP 5 (just upgraded from 4) and wanted to see if I missed anything beyond the advancements in OOP. Apparently, PHP.net is a much more thorough resource, but I did learn more string and array functions than I'll ever use. :roll:

One thing that bothered me in the book was when the author decided to mark elements of OOP that PHP doesn't support, and one of those things multiple inheritance.... The other was polymorphism. This instantly grabbed my attention as I said to myself, "What? Yes it does. What have we been discussing all of this time?" Here's what the book said:
PHP 5 For Dummies wrote:Object-Oriented concepts PHP 5 omits
[...]
Polymorphism: PHP does not allow more than one method, even a constructor, to have the same name in a class. Therefore, you can't implement polymorphism as you're used to doing. You can't have two or more methods with the same name in the same class that accept different types or number of variables. Some people use switches and other mechanisms to implement the functionality of polymorphism.
What?? This woman's credentials consist of over 20 years of programming experience. I mean, I caught one or two typos in the book, but that's a pretty big deal to confuse polymorphism and overloading in a book aimed at beginners.


I understand that the definition of polymorphism isn't always clear (as this discussion has proven), but overloading as always seemed clear to me, since I utilized it so often. Could it be that the author didn't mixed them up?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

superdezign wrote:I understand that the definition of polymorphism isn't always clear (as this discussion has proven), but overloading as always seemed clear to me, since I utilized it so often. Could it be that the author didn't mixed them up?
Some consider overloading a part of polymorphism, and it is, but there's more than just overloading in polymorphism.

And no multiple inheritance isn't really a big problem. If someone thinks it is, they're doing something wrong.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

feyd wrote:And no multiple inheritance isn't really a big problem. If someone thinks it is, they're doing something wrong.
Yeah, that's hardly a problem. You'd have to make very tiny, almost useless abstracts or base classes to need it, really.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

superdezign wrote:I understand that the definition of polymorphism isn't always clear (as this discussion has proven), but overloading as always seemed clear to me, since I utilized it so often. Could it be that the author didn't mixed them up?
That writer's quote show in classic fashion how blinkered we programmers can be about how to solve problems. She points out what to her is a limitation of PHP because she can't do this (a la C++):

Code: Select all

function foo ($bar) {
...
}
function foo ($bar, $baz) {
...
}
because she does not know how to do this:

Code: Select all

function foo ($bar, $baz=0) {
...
}
That's a good one.
(#10850)
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

lest not forget func_get_args() etc. too.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

:lol:

Well, in her defense, she does point out default parameter values for functions in the book, so she at least knows it's possible. :wink:


And, out of curiosity, is this a typo? I opened the book and it's the first thing that I read on the "cheat sheet" and I just thought to myself, "Either I'm wrong, or this book may not have been the best choice."
PHP 5 For Dummies wrote:Using empty brackets:

Code: Select all

$colors[]    = "red";
$colors[]    = "blue";
Result:

Code: Select all

$colors[1]   = "red";
$colors[2]   = "blue";
I could have sworn that this code would start the array off at the zero index, but when I think about it, I've grown used to using the foreach loop, so I've never checked.
Post Reply