Skip to content

Instantly share code, notes, and snippets.

@sunaot
Created July 26, 2011 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunaot/1106368 to your computer and use it in GitHub Desktop.
Save sunaot/1106368 to your computer and use it in GitHub Desktop.
<?php
// see https://gist.github.com/1106254 about toClosure() function.
class SpecificException extends Exception {};
class Sample
{
// Exectute Around Method and try-catch-finally sample in PHP.
function inLock($callback) {
$unlock = \toClosure(get_class(), 'unlock', $this);
$ensure = function() use($unlock) { $unlock(); };
$this->lock();
try {
$callback();
$ensure();
return;
} catch (SpecificException $e) {
// rescue specific case
$ensure();
return;
} catch (Exception $e) {
$ensure();
throw $e;
}
throw new Exception('you cannot be here.');
}
function lock() {
echo "lock", PHP_EOL;
}
function unlock() {
echo "unlock", PHP_EOL;
}
}
function usage() {
$obj = new Sample;
$obj->inLock(
function() {
echo "during execution", PHP_EOL;
}
);
}
usage();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment