Constructor overloading Java and PHP5
1 2 class Hoge { 3 4 public Hoge(){ 5 System.out.println("constructor 0"); 6 } 7 8 public Hoge(int a){ 9 System.out.println("constructor 1:" + a); 10 } 11 12 public Hoge(int a, String[] hoge){ 13 System.out.println("constructor 2:" + a + ":" + hoge); 14 } 15 16 public Hoge(A a, B b, C c){ 17 System.out.println("constructor 3:" + a + ":" + b + ":" + c); 18 } 19 }
PHP5 code
1 2 class Hoge { 3 4 public function __construct(){ 5 $num = func_num_args(); 6 $args = func_get_args(); 7 switch($num){ 8 case 0: 9 $this->__call('__construct0', null); 10 break; 11 case 1: 12 $this->__call('__construct1', $args); 13 break; 14 case 2: 15 $this->__call('__construct2', $args); 16 break; 17 case 3: 18 $this->__call('__construct3', $args); 19 break; 20 default: 21 throw new Exception(); 22 } 23 } 24 25 public function __construct0(){ 26 echo "constructor 0" . PHP_EOL; 27 } 28 29 public function __construct1($a){ 30 echo "constructor 1: " . $a . PHP_EOL; 31 } 32 33 public function __construct2($a, array $hoge){ 34 echo "constructor 2: " . $a . PHP_EOL; 35 var_dump($hoge); 36 } 37 38 public function __construct3(A $a, A $b, C $c){ 39 echo "constructor 3: " . PHP_EOL; 40 var_dump($a, $b, $c); 41 } 42 43 private function __call($name, $arg){ 44 return call_user_func_array(array($this, $name), $arg); 45 } 46 }
example(PHP5)
1 2 interface C { 3 const C = __CLASS__; 4 } 5 class A { 6 const A = __CLASS__; 7 private $a = array(1, 2, 3); 8 } 9 class B extends A{ 10 const B = __CLASS__; 11 private $b = array(1, 2, 3); 12 } 13 class D extends B implements C { 14 const D = __CLASS__; 15 private $c = array(1, 2, 3); 16 } 17 18 $a = new Hoge(); 19 $b = new Hoge(1); 20 $c = new Hoge(777, array(1,2,3)); 21 $d = new Hoge(new A(), new B(), new D());