Created
October 7, 2010 07:07
-
-
Save koshiaaaaan/614695 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 Koshian_File implements Iterator | |
{ | |
private $_lines = array(); | |
private $_index = 0; | |
public function __construct( $file, $flag = 0 ) | |
{ | |
if( file_exists( $file ) && is_readable( $file ) ) { | |
$this->_lines = file( $file, $flag ) ; | |
} | |
} | |
/** | |
* rewind()で呼べる | |
* インデックスのリセットメソッド | |
**/ | |
public function rewind() | |
{ | |
$this->_index = 0 ; | |
} | |
/** | |
* current()で呼べる | |
* 現在のインデックスが位置するデータを取得する | |
**/ | |
public function current() | |
{ | |
$k = array_keys( $this->_lines ) ; | |
$var = $this->_lines[ $k[ $this->_index ] ] ; | |
return $var; | |
} | |
/** | |
* key()で呼べる | |
* 現在のインデックスを取得する | |
**/ | |
public function key() | |
{ | |
$k = array_keys( $this->_lines ) ; | |
$var = $k[ $this->_index ] ; | |
return $var; | |
} | |
/** | |
* next()で呼べる | |
* インデックスを次にすすめ、そのインデックスが位置するデータを取得する | |
**/ | |
public function next() | |
{ | |
$k = array_keys( $this->_lines ) ; | |
if( isset( $k[ ++$this->_index ] ) ) { | |
$var = $this->_lines[ $k[ $this->_index ] ] ; | |
return $var ; | |
} else { | |
return false ; | |
} | |
} | |
/** | |
* データが存在するか否か | |
**/ | |
public function valid() | |
{ | |
$k = array_keys( $this->_lines ) ; | |
$var = isset( $k[ $this->_index ] ) ; | |
return $var ; | |
} | |
/** | |
* こういう独自のメソッドも組める。(これはマジックメソッドだけど) | |
* 文字列として扱うことが出来るよ | |
**/ | |
public function __toString() | |
{ | |
return join( '', $this->_lines ) ; | |
} | |
} | |
// ファイルを指定してインスタンス化 | |
$file = new Koshian_File( 'sample.txt' ) ; | |
// 配列と同じように使うことが出来る | |
foreach( $file as $line ) { | |
echo $line ; | |
} | |
// __toStringを実装してるので文字列としても扱える。 | |
// echo $file ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment