A defer statement originally comes from Golang. This library allows you to use defer functionality in PHP code.
<?phpdefer($context, $callback);
go_defer($context, $callback);defer and go_defer require two parameters: $context and $callback.
$context- unused in your app, required to achieve "defer" effect. I recommend to use$_always.$callback- a callback which is executed after the surrounding function returns.
defer executes callbacks First In, First Out. Functions execute in the order you deferred them.
go_defer more accurately emulates Golang's defer functionality and executes callbacks in Last In, First Out order.
<?phpfunctionhelloGoodbye()
{
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<?phpfunctionrollCall()
{
go_defer($_, function () {
echo"I was deferred first!\n";
});
go_defer($_, function () {
echo"I was deferred last!\n";
});
echo"I was NOT deferred!\n";
}
echo"before rollCall\n";
rollCall();
echo"after rollCall\n";
// Output://// before rollCall// I was NOT deferred!// I was deferred last!// I was deferred first!// after rollCall<?phpfunctionthrowException()
{
defer($_, function () {
echo"after exception\n";
});
echo"before exception\n";
thrownew \Exception('My exception');
}
try {
throwException();
} catch (\Exception$e) {
}
// Output://// before exception// after exceptionThis library is inspired by mostka/defer.