DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Constructor Overloading Java And PHP5

01.04.2007
| 13615 views |
  • submit to reddit
        Java's constructor overload

class Hoge {

    public Hoge(){
        System.out.println("constructor 0");
    }

    public Hoge(int a){
        System.out.println("constructor 1:" + a);
    }

    public Hoge(int a, String[] hoge){
        System.out.println("constructor 2:" + a + ":" + hoge);
    }

    public Hoge(A a, B b, C c){
        System.out.println("constructor 3:" + a + ":" + b + ":" + c);
    }
}

PHP5 code

class Hoge {

    public function __construct(){
        $num = func_num_args();
        $args = func_get_args();
        switch($num){
        case 0:
            $this->__call('__construct0', null);
            break;
        case 1:
            $this->__call('__construct1', $args);
            break;
        case 2:
            $this->__call('__construct2', $args);
            break;
        case 3:
            $this->__call('__construct3', $args);
            break;
        default:
            throw new Exception();
        }
    }

    public function __construct0(){
        echo "constructor 0" . PHP_EOL;
    }

    public function __construct1($a){
        echo "constructor 1: " . $a . PHP_EOL;
    }

    public function __construct2($a, array $hoge){
        echo "constructor 2: " . $a . PHP_EOL;
        var_dump($hoge);
    }

    public function __construct3(A $a, A $b, C $c){
        echo "constructor 3: " . PHP_EOL;
        var_dump($a, $b, $c);
    }

    private function __call($name, $arg){
        return call_user_func_array(array($this, $name), $arg);
    }
}

example(PHP5)

interface C {
    const C = __CLASS__;
}
class A {
    const A = __CLASS__;
    private $a = array(1, 2, 3);
}
class B extends A{
    const B = __CLASS__;
    private $b = array(1, 2, 3);
}
class D extends B implements C {
    const D = __CLASS__;
    private $c = array(1, 2, 3);
}

$a = new Hoge();
$b = new Hoge(1);
$c = new Hoge(777, array(1,2,3));
$d = new Hoge(new A(), new B(), new D());
    

Comments

Snippets Manager replied on Tue, 2007/01/16 - 11:39pm

Here's a prognosis: If the PHP-Developers will not implement appropiate object oriented programming techniques like overloading, polymorphism and mupltiple inheritance soon, then there is going to be a lynching. Anyway: Good workaround.