✨ Defer for PHP (like in Go)
Never forget to close a file, release a lock, or roll back a transaction again. defer() runs your cleanup exactly when the function returns — even on early return or exceptions.
composer require tito10047/php-defer

Repo: https://github.com/tito10047/php-defer
#PHP #Go #defer #CleanCode #Symfony

@tito100 Is there a specific benefit in using it as a replacement for try {…} finally {…} ?
@ausi yes. Imagine that you want open two files. This two files Has fclose in finaly. But after open succesfuly fist filé open, something failed and second filé IS not opened. In finaly IS crashed because you try to close not opened file
@tito100 You would have to nest the try/finally blocks in that case I think, but that would result in deeply nested and unreadable code. I agree that for such use cases defer() seems like a nicer solution. ⭐️

@tito100 @ausi

I've being doing this for years:

```
try {
$f1 = fopen('...');
$f2 = fopen('...');
} finally {
is_resource($f1 ?? null) and fclose($f1);
is_resource($f2 ?? null) and fclose($f2);
}
```

@tito100 nice implementation. Do you know the `php-defer/php-defer` implementation? It's a pretty efficient solution build around the (LIFO) SplStack:

https://github.com/php-defer/php-defer

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

Golang's defer statement for PHP. Contribute to php-defer/php-defer development by creating an account on GitHub.

GitHub
@lukasrotermund yes, that IS inspired by this me library. Look at end readme that library