多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 实例 ~~~ class FileException extends Exception{ public function getDetails() { switch($this->code){ case 0: return "没有提供文件"; break; case 1: return "文件不存在"; break; case 2: return "不是一个文件"; break; case 3: return "文件不可写"; break; case 4: return "非法文件的操作模式"; break; case 5: return "文件写入失败"; break; case 6: return "文件不能被关闭"; break; default: return "非法操作"; break; } } } class WriteDate{ private $_message = ''; private $file; public function __construct($filename = null, $mode = 'w') { $this->_message = "文件:" . $filename . ",模式:" . $mode; if(empty($filename)) throw new FileException($this->_message, 0); if(!file_exists($filename)) throw new FileException($this->_message, 1); if(!is_file($filename)) throw new FileException($this->_message, 2); if(!is_writeable($filename)) throw new FileException($this->_message, 3); if(!in_array($mode, ['w', 'w+', 'a', 'a+'])) throw new FileException($this->_message, 4); $this->file = fopen($filename, $mode); } public function write($data) { if(@!fwrite($this->file, $data . PHP_EOL)) throw new FileException($this->_message, 5); } public function close() { if($this->file){ if(@!fclose($this->file)) throw new FileException($this->_message,6); } } } ~~~ 测 ~~~ try{ $file = new WriteDate('./1.txt', 'w+'); //,假如文件不存在 . $file->write("Hello World"); } catch(FileException $e){ echo $e->getDetails(); } ~~~ 结果 ~~~ 文件不存在 //抛出异常,稳如文件存在,就会写入Hello World ~~~