Page 1 of 1
Polymorphism
Posted: Sun Nov 13, 2005 10:41 pm
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!
Posted: Sun Nov 13, 2005 11:13 pm
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.
Posted: Mon Nov 14, 2005 4:20 am
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
Posted: Mon Nov 14, 2005 7:18 pm
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.