Skip to content

Instantly share code, notes, and snippets.

@jdefez
Last active October 18, 2021 18:00
Show Gist options
  • Save jdefez/e7624ec1b414bb82a430e3e5d29b59ec to your computer and use it in GitHub Desktop.
Save jdefez/e7624ec1b414bb82a430e3e5d29b59ec to your computer and use it in GitHub Desktop.
Extending SplTempFileObject with a store method
class TmpFile extends SplTempFileObject
{
public function store(string $filename): void
{
file_put_contents($filename, $this->getContents());
}
public function getContents(): ?string
{
$this->rewind();
ob_start();
$this->fpassthru();
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
}
// Usage
$filepath = __DIR__ . '/file.txt';
$file = new TmpFile();
$file->fwrite('Lorem dolor sit amet');
$file->fwrite('...');
$file->store($filepath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment