Skip to content

Instantly share code, notes, and snippets.

@bigwhoop
Created November 12, 2012 17:13
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 bigwhoop/4060588 to your computer and use it in GitHub Desktop.
Save bigwhoop/4060588 to your computer and use it in GitHub Desktop.
deferred statements in php
'defer' puts statements on a LIFO stack and executes them right before the function returns.
<?php
function fooz() { function fooz() {
defer echo 'bai';
defer echo 'thx'; ... becomes ...
echo 'k'; echo 'k';
echo 'thx';
echo 'bai';
} }
?>
'defer' helps to re-use clean-up code and to preserve contexts.
<?php
function f($a = true) {
$fh = fopen('file.txt', 'r');
if (!$fh) {
return false;
}
defer fclose($fh);
if ($a) {
// do stuff ...
return 'something';
}
// do other stuff ...
return 'something different';
}
?>
... becomes ...
<?php
function f($a = true) {
$fh = fopen('file.txt', 'r');
if (!$fh) {
return false;
}
if ($a) {
// do stuff ...
$ret = 'something';
fclose($fh);
return $ret;
}
// do other stuff ...
$ret = 'something different';
fclose($fh);
return $ret;
}
?>
Finally a silly example with a closure.
<?php
function foo($i) {
defer function() use (&$i) {
$i++;
}();
$i *= 10;
return $i;
}
?>
... becomes ...
<?php
function foo($i) {
$i *= 10;
function() use (&$i) {
$i++;
}()
return $i;
}
?>
<?php
foo(1); // 11
foo(5); // 51
foo(20); // 201
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment