Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Constructor Overloading Java And PHP5

DZone's Guide to

Constructor Overloading Java And PHP5

·
Free Resource
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());
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}