Skip to content

Instantly share code, notes, and snippets.

@uu59
Created March 16, 2011 13:26
Show Gist options
  • Save uu59/872484 to your computer and use it in GitHub Desktop.
Save uu59/872484 to your computer and use it in GitHub Desktop.
<?php
class File {
private $fp = null;
function __construct($path) {
$this->path = $path;
}
function open($mode) {
if($this->fp) {
throw new Exception('file is already opened');
}
$this->fp = fopen($this->path, $mode);
}
function close() {
if(! $this->fp) {
throw new Exception('file is not opened');
}
fclose($this->fp);
}
function puts($data) {
if(! $this->fp) {
throw new Exception('file is not opened');
}
fputs($this->fp, $data);
}
function read() {
return file_get_contents($this->path);
}
static function openWith($filepath, $mode, $fn) {
$file = new self($filepath);
$file->open($mode);
$fn($file);
$file->close();
}
}
$file = new File('/tmp/a.txt');
$file->open('a');
foreach(range(1,10) as $n) {
$file->puts("{$n}\n");
}
$file->close();
echo $file->read(); // 1\n2\n ... 10\n
File::openWith('/tmp/b.txt', 'a', function($file) {
$file->puts("aaa\n");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment