SplFileObject::__construct

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

SplFileObject::__constructConstruct a new file object

說(shuō)明

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

Construct a new file object.

參數(shù)

filename

The file to read.

小技巧

如已啟用fopen 包裝器,在此函數(shù)中, URL 可作為文件名。關(guān)于如何指定文件名詳見(jiàn) fopen()。各種 wapper 的不同功能請(qǐng)參見(jiàn) 支持的協(xié)議和封裝協(xié)議,注意其用法及其可提供的預(yù)定義變量。

mode

The mode in which to open the file. See fopen() for a list of allowed modes.

useIncludePath

Whether to search in the include_path for filename.

context

A valid context resource created with stream_context_create().

錯(cuò)誤/異常

Throws a RuntimeException if the filename cannot be opened.

Throws a LogicException if the filename is a directory.

范例

示例 #1 SplFileObject::__construct() example

This example opens the current file and iterates over its contents line by line.

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

參見(jiàn)