ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Object Overloading in PHP 5
Subject:   method overloading ala C++/Java
Date:   2005-07-17 13:56:25
From:   MartinJansen
Response to: method overloading ala C++/Java

PHP 5 does not support polymorphism as you know it from Java or C++, but you can sort of emulate it.



function foo($arg1, $arg2 = null) {
if (!isset($arg2)) {
$arg2 = 42;
}


return $arg1 + $arg2;
}


is "equivalent" to the following Java code:



public int foo(int arg1, int arg2) {
return arg1 + arg2;
}


public int foo(int arg1) {
return foo(arg1, 42);
}


In a similar manner you can support homonymous methods with different parameter types:



function foo($arg1) {
if (!is_array($arg1)) {
$arg1 = array($arg1);
}


/* ... */
}


is "equivalent" to the following Java (pseudo-)code:



public void foo(HashTable arg1) {
/* ... */
}


public void foo(int arg1) {
HashTable a = new HashTable;
a.push(arg1);
foo(a);
}


1 to 1 of 1
  1. method overloading ala C++/Java
    2005-10-04 08:08:40  trollll [View]

1 to 1 of 1