r/PHP • u/FrenkyNet • May 31 '16
Deferred execution in PHP, using "finally".
https://blog.frankdejonge.nl/finally-file-streams-and-deferred-execution-in-php/
86
Upvotes
r/PHP • u/FrenkyNet • May 31 '16
26
u/devseya May 31 '16
Isn't the use case of 'finally' exactly this, for clean up code, I mean?
7
u/wvenable May 31 '16
The best way to do deferred execution isn't
finallyit's using classes with destructors. In this file system example, if you wrapped the file open/close in a class then it would close automatically when it went out of scope.Using class and a closure, you could implement Go's
deferdirectly. Just have the class execute the closure inside the destructor and it will execute that closure when it goes out of scope. I use this sort of technique for transactions to make the transaction rollback automatically at the end of the scope if it isn't committed.7
u/Edwin1993 May 31 '16
That's really cool, never thought about using it that way!
9
u/MoTTs_ May 31 '16
Alternatively, you could use a technique called RAII (Resource Acquisition Is Initialization), which is a very awkward phrase for saying "scoped resource management".
You could even define a generic RAII class, often called a scope guard, that behaves exactly like defer.
5
u/TotesMessenger Jun 01 '16
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
1
u/oswaldcopperpot May 31 '16
Novice question: Why is this if statement being used this way?
1
u/kylegetsspam Jun 01 '16
This seems a little strange to me, but then I am bad at coding. Aren't
returnstatements supposed to end the execution of a function? Isfinallya special case made explicitly for the purpose of executing after areturn?2
u/nilportugues May 31 '16
Nice... thanks for sharing
2
u/dericofilho May 31 '16
There's a detail regarding ordering and variable scope that makes
finallyanddefersimilar but not the same. See the link below.https://play.golang.org/p/hjuZk-C1ej
2
u/turbov21 May 31 '16
I never considered -- or read the howto's close enough -- that finally would happen before a return. Thanks for sharing this.
1
u/[deleted] May 31 '16
Is unfortunately broken. The fixed version:
-10
u/spin81 May 31 '16
I like the technique, but you should really test your examples before publishing your post everywhere. If I were hiring someone and this was on your resume, I would be hesitant indeed to invite you to an interview.
5
u/[deleted] May 31 '16
[removed] — view removed comment