Last active
October 18, 2021 18:00
-
-
Save jdefez/e7624ec1b414bb82a430e3e5d29b59ec to your computer and use it in GitHub Desktop.
Extending SplTempFileObject with a store method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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