Created
March 16, 2011 13:26
-
-
Save uu59/872484 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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