(PHP >= 5.3) If filename is a directory, a LogicException will be thrown: "Cannot use SplFileObject with directories"
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject::__construct — 新しいファイルオブジェクトを作成する
$filename
, string $open_mode
= "r"
, bool $use_include_path
= false
, resource $context
= ?
)新しいファイルオブジェクトを作成します。
filename
読み込むファイル。
fopen wrappers が有効の場合、この関数のファイル名として URL を使用することができます。ファイル名の指定方法に関する詳細は fopen() を参照ください。 サポートするプロトコル/ラッパー には、さまざまなラッパーの機能やその使用法、 提供される定義済み変数などの情報がまとめられています。
open_mode
ファイルをオープンするときのモード。許可されるモードのリストは fopen() を参照。
use_include_path
filename
を探すのに include_path を探索するかどうか。
context
stream_context_create() で作られる有効なコンテキストリソース。
値を返しません。
filename
がオープンできない場合、RuntimeException がスローされます。
filename
がディレクトリの場合、LogicException がスローされます。
例1 SplFileObject::__construct() の例
この例は現在のファイルをオープンし 1 行ごとに内容を反復処理します。
<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line_num => $line) {
echo "Line $line_num is $line";
}
?>
上の例の出力は、 たとえば以下のようになります。
Line 0 is <?php Line 1 is $file = new SplFileObject(__FILE__); Line 2 is foreach ($file as $line_num => $line) { Line 3 is echo "Line $line_num is $line"; Line 4 is } Line 5 is ?>
(PHP >= 5.3) If filename is a directory, a LogicException will be thrown: "Cannot use SplFileObject with directories"
When using URL as a filename, such as "http://..." or "php://stdin", and also have the fopen wappers on, and you get a 'RuntimeException' error, try using "NoRewindIterator" class to a SplFileObject instance.
<?php
$url = 'http://sample.com/data.csv';
$file = new NoRewindIterator( new SplFileObject( $url ) );
foreach ($file as $line_num => $line) {
echo "Line $line_num is $line";
}
?>
While opening a file, a rewind method will be called, but these URL iterators cannot be rewind, so you'll get a "Fatal error: Uncaught exception 'RuntimeException' with message 'Cannot rewind file ...'" error.