Enforce the Disposal of Objects in PHP


October 22nd, 2021

Enforce the Disposal of Objects in PHP

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:

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()` implementation
function using(Disposable $disposable, callable $callback): void
try {
} finally {
// 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.

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.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.