Download the PHP package tito10047/php-defer without Composer
On this page you can find all versions of the php package tito10047/php-defer. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package php-defer
In short
Defer lets you schedule a cleanup action to run at the end of the current function/block. Use it right after acquiring a resource so you never forget to release it, even if you return early or an exception is thrown. Typical use cases include closing files, unlocking mutexes, or rolling back transactions.
Example:
php-defer
A php implementation of defer statement from Go
PHP defer function schedules a function call (the deferred function) to be run immediately before the function executing the defer returns. It's an unusual but effective way to deal with situations such as resources that must be released regardless of which path a function takes to return. The canonical examples are unlocking a mutex or closing a file.
Deferring a call to a function such as Close has two advantages. First, it guarantees that you will never forget to close the file, a mistake that's easy to make if you later edit the function to add a new return path. Second, it means that the close sits near the open, which is much clearer than placing it at the end of the function.
Installation
Quick example
will print
3 Rules
The behavior of defer statements is straightforward and predictable. There are three simple rules:
1.
A deferred function's arguments are evaluated when the defer statement is evaluated.
In this example, the expression "i" is evaluated when the printf call is deferred.
The deferred call will print 0
after the function returns.
will print
2.
Deferred function calls are executed in Last In First Out order after the
surrounding function returns.
This function prints 3210
:
3.
Deferred functions can`t modify return values when is type, but can modify content of
reference to array or object.
In this example, a deferred function increments increment $o->i
after the surrounding
function returns but not modify returned $i
. This example print 2-3
:
PHP Limitations
- In php defer implementation you can't modify returned value. Can modify only content of returned reference
- You need instantiate defer object before use it with or