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

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

Polymorphism

Post by abalfazl »

Hello firends


From PHP 5 mysql Bible(Page 373) :


There should be only one constructor function per class definition. Defining more than one such function is syntactically legal, but pointless, as only the definition that occurs last will be in effect. If you’d like to have different constructors to handle different numbers and types of input arguments,


What is relationship between "different constructors to handle different numbers and types of
input arguments" and "polymorphism"?


Thanks in advance,
GOOD LUCK!
Last edited by abalfazl on Mon Nov 14, 2005 4:17 am, edited 1 time in total.
Cogs
Forum Newbie
Posts: 17
Joined: Thu Mar 27, 2003 4:57 pm

Post by Cogs »

In the quote it looks like the author is talking about overloading a constructor to handle different input. Whereas polymorphism, in an OOP language, is the ability for programmer to override a method of the parent class.

Edit: I probably should explain what overloading is.
Overloading is the abilityo to create methods in the same class with the exact same name, but with different arguments (the signature). When the overloaded name is requested, the actual method that is executed will depend whether or not the arguments match what the method expects.
abalfazl
Forum Commoner
Posts: 71
Joined: Mon Sep 05, 2005 10:05 pm

Post by abalfazl »

Hello firends

In the quote it looks like the author is talking about overloading a constructor to handle different input. Whereas polymorphism, in an OOP language, is the ability for programmer to override a method of the parent class.

May you give me a code example about what you said?

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

Post by Jenk »

From what I understand, polymorphism is not just the ability to over-ride parent classes, but for the class itself to be able to adapt/change to the object, and what the object is going to be.. the simplest example, which I saw on another site (I can't remember where, sorry) is about shapes:

Code: Select all

<?php

class Shape
{
    var $sides; //number of sides

    function Shape() 
    {
        if (func_num_args() == 3) {
            $this->sides = 3;
        } elseif (func_num_args() == 4) {
            $this->sides = 4;
        } else {
            //etc.
        }
    }
}

$triangle = new Shape($x, $y, $z);
$square = new Shape($a, $b, $c, $d);

?>
Another simple form would be using data type, name checking what type the data is (int/str/bool etc.) and adapting where necessary.
Post Reply