Created
November 12, 2012 17:13
-
-
Save bigwhoop/4060588 to your computer and use it in GitHub Desktop.
deferred statements in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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