Skip to content

Simple PHP emulation of C++'s SCOPE_EXIT, or GoLang's defer.

License

Notifications You must be signed in to change notification settings

phplang/scope-exit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ScopeExit

This simple class provides an implementation of C++'s SCOPE_EXIT, or GoLang's defer.

To use, assign an instance of this object to a local variable. When that variable falls out of scope (or is explicitly unset), the callback passed to the constructor will be invoked. This is useful, for example, to aid cleanup at the end of a function.

function f(&$x) {
  $x = 1;
  $_ = new \PhpLang\ScopeExit(function() use (&$x) { $x = 2; });
  // $x is still 1 at this point.
  return 42;
  // After the return, the local scope is cleaned up, the closure is invoked, and it's set to 2
}

f($a);
var_dump($a); // int(2)

About

Simple PHP emulation of C++'s SCOPE_EXIT, or GoLang's defer.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages