簡體   English   中英

從SplFileInfo對象獲取流資源

[英]Get a stream resource from a SplFileInfo object

我正在調用一個期望文件的流資源的方法,如下所示:

$obj->method(fopen($splFileInfo, 'r+'));

$splFileInfo對象的實例SplFileInfo

有沒有辦法獲取$splFileInfo對象的流資源而無需調用fopen

您可以使用openfile創建SplFileObject ,它提供與資源類似的功能,但是以面向對象的方式。 缺點是它不會直接暴露它包裝的資源,因此您必須調整現在期望資源使用SplFileObject的任何實現。

一些示例代碼向您展示我的意思:

class TextReader {
  public function getFirstLine(SplFileInfo $file): string {
      return $file->fgets();
    }
}

$splFileInfo = new SplFileInfo('filename.txt');
$splFileObject = $splFileInfo->openFile('r+');
$reader = new TextReader();
echo $reader->getFirstLine($splFileObject);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM