且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

面向对象编程,类切换

更新时间:2022-08-12 17:51:28

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
<?php
abstract class ParamHandler{
    protected $source;
    protected $param 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语句,然后对应写上子类
        if (preg_match("/\.xml$/i"$filename)) {
            return new XmlParamHandle($filename);
        }
        return new TextParamHandler($filename);
    }
 
    abstract function write();  //保证子类实现这两个方法
    abstract function read();
}
 
 
?>

然后下面是子类

1
2
3
4
5
6
7
8
9
10
11
12
class XmlParamHandle extends ParamHdndle{
    function write(){}
 
    function read(){}
}
 
 
class TextParamHandle extends ParamHdndle{
    function write(){}
 
    function read(){}
}

这样实例化的时候可以这样子

$test = ParamHandler::getInstance("./params.xml");

这样根据传入的params.xml文件会找到对应的类实例化。

本文转自  陈小龙哈   51CTO博客,原文链接:http://blog.51cto.com/chenxiaolong/1695800