You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The defer statement originally comes from Golang. This library allows you to use the defer functionality in your PHP code.
Usage
<?phpdefer($context, $callback);
defer requires two parameters: $context and $callback.
$context - unused in your app, required to achieve the "defer" effect. I recommend to use $_ always.
$callback - a callback which is executed after the surrounding function returns.
Examples
Defer the execution of a code
<?phpfunctionhelloGoodbye()
{
defer($_, function () {
echo"goodbye\n";
});
defer($_, function () {
echo"...\n";
});
echo"hello\n";
}
echo"before hello\n";
helloGoodbye();
echo"after goodbye\n";
// Output://// before hello// hello// ...// goodbye// after goodbye
Defer and exceptions
<?phpfunctionthrowException()
{
defer($_, function () {
echo"after exception\n";
});
echo"before exception\n";
thrownew \Exception('My exception');
}
try {
throwException();
} catch (\Exception$e) {
echo"exception has been caught\n";
}
// Output://// before exception// after exception// exception has been caught
Installation
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.