CakeFest 2024: The Official CakePHP Conference

SplFileObject::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::__construct新しいファイルオブジェクトを作成する

説明

public SplFileObject::__construct(
    string $filename,
    string $mode = "r",
    bool $useIncludePath = false,
    ?resource $context = null
)

新しいファイルオブジェクトを作成します。

パラメータ

filename

読み込むファイル。

ヒント

fopen wrappers が有効の場合、この関数のファイル名として URL を使用することができます。ファイル名の指定方法に関する詳細は fopen() を参照ください。 サポートするプロトコル/ラッパー には、さまざまなラッパーの機能やその使用法、 提供される定義済み変数などの情報がまとめられています。

mode

ファイルをオープンするときのモード。許可されるモードのリストは fopen() を参照。

useIncludePath

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 ?>

参考

add a note

User Contributed Notes 2 notes

up
0
KEINOS at blog.keinos.com
6 years ago
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.
up
-3
majna
9 years ago
(PHP >= 5.3) If filename is a directory, a LogicException will be thrown: "Cannot use SplFileObject with directories"
To Top