Enforce the Disposal of Objects in PHP
Published on by Paul Redmond
The using PHP package by Ryan Chandler enforces the disposal of objects in PHP. Inspired by Hack and C#, this package is useful when working with file handles:
✨ Just released a new package that brings pseudo-disposal to your PHP code. Inspired by Hack and C#, the `using()` function and `Disposable` interface will enforce disposal of objects. Useful when working will file handles and similar. https://t.co/aEd0jje9mR
— Ryan Chandler (@ryangjchandler) October 19, 2021
The package contains a Disposable
interface and a global using()
function to ensure object disposal.
Given the following class in the readme:
use RyanChandler\Using\Disposable; class TextFile implements Disposable{ private $resource; public function dispose(): void { $this->resource = fclose($this->resource); }}
The using()
helper ensures the dispose()
method is called even in the event of an exception via finally
:
// Simple `using()` implementationfunction using(Disposable $disposable, callable $callback): void{ try { $callback($disposable); } finally { $disposable->dispose(); }} // Example usage$file = new TextFile('hello.txt');using($file, function (TextFile $file) { DB::create('messages', [ 'message' => $file->contents(), ]);}); // The `$resource` property is no-longer a valid stream,// since we closed the handle in the `dispose` method.var_dump($file->resource);
You can learn more about this package, get full installation instructions, and view the source code on GitHub. In C#, you can learn more about the using statement, which inspired this package.