39

GitHub - php-defer/php-defer: Golang's defer statement for PHP

 4 years ago
source link: https://github.com/php-defer/php-defer
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK