<?php class errorObject { private $__error; public function __construct($error) { $this->__error = $error; } public function getError() { return $this->__error; } } class logToConsole { private $__errorObject; public function __construct($errorObject) { $this->__errorObject = $errorObject; } public function write() { fprintf ( STDERR, $this->__errorObject->getError () ); } } /** * 外部須要的數據對象. * @author michile * */ class logToCsv { const CSV_LOCATION = 'log.csv'; private $__errorObject; public function __construct($errorObject) { $this->__errorObject = $errorObject; } public function write() { $line = $this->__errorObject->getErrorNumber (); $line .= ','; $line .= $this->__errorObject->getErrorText (); $line .= '\n'; file_put_contents ( self::CSV_LOCATION, $line, FILE_APPEND ); } } /** * 適配器生成新的方法,來匹配到合適的格式. * @author michile * */ class logToCSVAdapter extends errorObject { private $__errorNumber,$__errorText; public function __construct($error) { parent::__construct($error); $parts=explode(':', $this->getError()); //此處$this->getError()的用法. $this->__errorNumber=$parts[0]; $this->__errorText=$parts[1]; } // 實現拓展方法. public function getErrorNumber() { return $this->__errorNumber; } public function getErrorText() { return $this->__errorText; } } $error=new logToCSVAdapter('400:Not Found'); $log=new logToCsv($error); $log->write();