Skip to content


Repository files navigation

PHP Defer

Coverage Status Tests status

The defer statement originally comes from Golang. This library allows you to use the defer functionality in your PHP code.



defer($context, $callback);

defer requires two parameters: $context and $callback.

  1. $context - unused in your app, required to achieve the "defer" effect. I recommend to use $_ always.
  2. $callback - a callback which is executed after the surrounding function returns.


Defer the execution of a code


function helloGoodbye()
    defer($_, function () {
        echo "goodbye\n";

    defer($_, function () {
        echo "...\n";

    echo "hello\n";

echo "before hello\n";
echo "after goodbye\n";

// Output:
// before hello
// hello
// ...
// goodbye
// after goodbye

Defer and exceptions


function throwException()
    defer($_, function () {
        echo "after exception\n";

    echo "before exception\n";

    throw new \Exception('My exception');

try {
} catch (\Exception $e) {
    echo "exception has been caught\n";

// Output:
// before exception
// after exception
// exception has been caught


PHP Defer supports all PHP versions from ^5.3 to ^8.0. The following command will install the latest possible version of PHP Defer for your PHP interpreter.

composer require "php-defer/php-defer:^3.0|^4.0|^5.0"


This library is inspired by mostka/defer.