Amit Shah

An IT Professional

Object Oriented Programming in PHP - Overloading PDF Print E-mail
User Rating: / 0
Overloading (which is different from overriding) is not supported in PHP. In OOP you "overload" a method when you define two/more methods with the same name but different number or type of parameters (depending upon the language).

PHP is a loosely typed language so overloading by types won't work, however overloading by number of parameters doesn't work either.

It's very nice sometimes in OOP to overload constructors so you can build the object in different ways (passing different number of arguments). A trick to do something like that in PHP is:


class Myclass {
function Myclass() {
//Note that $this->$name() is usually wrong but here
//$name is a string with the name of the method to call.

function Myclass1($x) {
function Myclass2($x,$y) {


With this extra working in the class the use of the class is transparent to the user:

$obj1=new Myclass('1'); //Will call Myclass1
$obj2=new Myclass('1','2'); //Will call Myclass2

Sometimes this is very nice.


Polymorphism is defined as the ability of an object to determine which method to invoke for an object passed as argument in runtime time. For example if you have a class figure which defines a method draw and derived classes circle and rectangle, where you override the method draw you might have a function which expects an argument x and then call $x->draw().

If you have polymorphism the method draw called depends of the type of object you pass to the function.

Polymorphism is very easy and natural in interpreted languages as PHP (try to imagine a C++ compiler generating code for this case, which method do you call? You don't know yet which type of object you have! OK, this is not the point).

So PHP happily supports polymorphism.


function niceDrawing($x) {
//Supose this is a method of the class Board.

$obj=new Circle(3,187);
$obj2=new Rectangle(4,5);

$board->niceDrawing($obj); //will call the draw method of Circle.
$board->niceDrawing($obj2); //will call the draw method of Rectangle.


< Prev   Next >

Tag Here