Women in Technology

Hear us Roar



Article:
  Object Overloading in PHP 5
Subject:   method overloading ala C++/Java
Date:   2005-07-15 03:47:50
From:   simoncpu
Is there a straightforward way to overload methods having the same name but with different number of parameters? Can you please share a technique to do that?


Thanks.


[ simon.cpu]

Main Topics Newest First

Showing messages 1 through 1 of 1.

  • method overloading ala C++/Java
    2005-07-17 13:56:25  MartinJansen [View]

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