Java 与 PHP5 的构造函数重载

Jun 29th, 2007 | Filed under PHP

Java Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);
    }
}
Tags: ,
Comments are closed.