小实验 – 直接调用抽象方法内的静态方法来实例化子类

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
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
 
abstract class ParamHandler{
    protected $source;
    protected $params array();
 
    function __construct($source){
        $this->source = $source;
    }
 
    function addParam($key$val){
        $this->params[$key] = $val;
    }
 
    function getAllParams(){
        return $this->params;
    }
 
    static function getInstance($filename){
        if(preg_match("/\.xml$/i"$filename)){
            return New XmlParamHandler($filename);
       }
 
       return New TextParamHandler($filename);
    }
 
    abstract function write();
    abstract function read();
}
 
class XmlParamHandler extends ParamHandler{
    function read(){
        echo 'XmlParamHandler Read.';
    }
 
    function write(){
        echo 'XmlParamHandler Write.';
    }
}
 
class TextParamHandler extends ParamHandler{
    function read(){
        echo 'TextParamHandler Read.';
    }
 
    function write(){
        echo 'TextParamHandler Write.';
    }
}
 
//抽象方法不能直接实例化,直接调用抽象方法内的静态方法来实例化子类
//这样也行 尼玛......
$test = ParamHandler::getInstance("./params.xml");
$test->addParam("key1","value1");
$test->addParam("key2","value2");
$test->addParam("key3","value3");
$test->write();
?>