单件模式即singleton pattern(属于创建型设计模式),最适合解释的例子就是日志记录了.
其他模式的php代码以后写好了在分享给大家,希望可以增加点大家对php中设计模式的概念.
复制内容到剪贴板
代码:__fp = @fopen('application.log', 'ab+')){
$this->__errmsg = '创建或读取日志文件失败';
$this->__errorhandler();
}
}
#析构函数,释放资源
function __destruct(){
#站位先
}
#静态函数,配合静态变量使用,实现singleton设计模式
static function getinstance(){
if(self::$__instance == null){
self::$__instance = new log;
}
return self::$__instance;
}
#类内部错误处理机制
private function __errorhandler(){
die($this->__errmsg);
}
#将指定内容写入到日志文件中
public function inlog($temp){
if(@fwrite($this->__fp, time().|||.$temp.\r\n) === false){
$this->__errmsg = '写入到日志文件失败';
$this->__errorhandler();
}
return;
}
#将日志内容输出,参数默认为1,即默认用类内部方法打印日志,否则可自定义显示方式.两种情况下都返回数组
public function outlog($default = 1){
$outarray = array();
while(!feof($this->__fp)){
$line = fgets($this->__fp);
if(strlen($line) != 0){
$tmp = explode(|||, $line, 2);
$outarray[] = $tmp;
}
}
if($default == 1){
$this->__printlog($outarray);
}
return $outarray;
}
#默认日志输出方式
private function __printlog($arr){
foreach($arr as $temp){
echo '记录时间:'.date('y-m-d h:m:s' , $temp[0]).'
原因:'.$temp[1].'
';
}
}
#私有变量,初始化每个变量
static private $__instance = null;
private $__fp = null;
private $__errmsg = '';
}
?>附上测试文件
代码:inlog($e->getmessage());
}
?>
