Women in Technology

Hear us Roar



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);
}

Full Threads Newest First

Showing messages 1 through 1 of 1.

  • method overloading ala C++/Java
    2005-10-04 08:08:40  trollll [View]

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


    return $arg1 + $arg2;
    }

    why not just say:
    function foo($arg1, $arg2 = 42) {
    return $arg1 + $arg2;
    }

    other than that, glad to see someone else misses polymorphism. i wish i had the time to add it myself... i haven't checked the game plan on future releases lately - anyone know when and if i can start looking forward to this?