Skip to content
Golang's defer statement for PHP
PHP Shell
Branch: master
Clone or download
Latest commit 979426e Oct 9, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
bin Version 2.0 (#1) Oct 8, 2019
dev-tools Version 2.0 (#1) Oct 8, 2019
src Version 2.0 (#1) Oct 8, 2019
tests Version 2.0 (#1) Oct 8, 2019
.coveralls.yml Initial public release Oct 8, 2019
.gitattributes Initial public release Oct 8, 2019
.gitignore Initial public release Oct 8, 2019
.php_cs.dist
.travis.yml Version 2.0 (#1) Oct 8, 2019
CHANGELOG.md Version 2.0 (#1) Oct 8, 2019
LICENSE Initial public release Oct 8, 2019
README.md Typo in README.md Oct 9, 2019
composer.json Version 2.0 (#1) Oct 8, 2019
phpunit.xml.dist Initial public release Oct 8, 2019

README.md

PHP Defer

Coverage Status Build Status

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

Usage

<?php

defer($context, $callback);

defer requires two parameters: $context and $callback.

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

Examples

Defer the execution of a code

<?php

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

    echo "hello\n";
}

echo "before hello\n";
helloGoodbye();
echo "after goodbye\n";

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

Defer and exceptions

<?php

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

    echo "before exception\n";

    throw new \Exception('My exception');
}

try {
    throwException();
} catch (\Exception $e) {
}

// Output:
//
// before exception
// after exception

Credits

This library is inspired by mostka/defer.

You can’t perform that action at this time.