English | 简体中文 | 繁體中文
查询

streamWrapper::stream_close()函数—用法及示例

「 关闭当前打开的流 」


函数名称:streamWrapper::stream_close()

适用版本:PHP 4 >= 4.3.2, PHP 5, PHP 7

函数描述:stream_close() 函数用于关闭当前打开的流。

语法:bool streamWrapper::stream_close(void)

参数:

  • 无参数。

返回值:

  • 如果流成功关闭,则返回 true。如果关闭失败,则返回 false。

示例:

class MyStreamWrapper
{
    private $handle;

    public function stream_open($path, $mode, $options, &$opened_path)
    {
        $this->handle = fopen($path, $mode);
        return $this->handle !== false;
    }

    public function stream_read($count)
    {
        return fread($this->handle, $count);
    }

    public function stream_write($data)
    {
        return fwrite($this->handle, $data);
    }

    public function stream_close()
    {
        fclose($this->handle);
        return true;
    }
}

stream_wrapper_register("mywrapper", "MyStreamWrapper");

$handle = fopen("mywrapper://example.txt", "r");
if ($handle) {
    echo fread($handle, filesize("mywrapper://example.txt"));
    fclose($handle);
}

// 输出:This is the content of example.txt file.

在上面的示例中,我们创建了一个自定义的流包装器 MyStreamWrapper,其中包含了 stream_open()stream_read()stream_write()stream_close() 方法。在 stream_open() 方法中,我们打开了一个文件并将其句柄存储在 $handle 属性中。在 stream_close() 方法中,我们使用 fclose() 函数关闭了该句柄,并返回 true 表示关闭成功。在使用自定义流包装器时,我们可以通过 mywrapper:// 协议访问文件,如示例中的 fopen("mywrapper://example.txt", "r")。最后,我们通过读取文件内容并关闭文件句柄来展示了 stream_close() 方法的使用。

补充纠错
热门PHP函数
分享链接