Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active March 28, 2016 18:11
Show Gist options
  • Save lsloan/ba5d2f5e3f4f2bd2e6ec to your computer and use it in GitHub Desktop.
Save lsloan/ba5d2f5e3f4f2bd2e6ec to your computer and use it in GitHub Desktop.
PHP: Inconsistent try...finally blocks are expected to return the same value, but don't.
<?php
function fubar1($foo = 1){
_($foo, 1);
try{
$foo++; // even works when $foo modified in this block
_($foo);
return $foo; // only works when bare $foo returned
} finally {
_($foo);
$foo++;
_($foo);
}
}
function fubar2($foo = 1){
_($foo, 1);
try{
$foo++;
_($foo);
return $foo + 0;
// it also happens when returning...
// intval($foo), strval($foo), -(-$foo), +$foo
} finally {
_($foo);
$foo++; // this is ignored
_($foo);
}
}
function _($x, $n = null) {
global $m;
$m = is_null($n) ? ++$m : $n;
print " Step ${m}: $x" . PHP_EOL;
}
print 'Result 1: ' . fubar1() . PHP_EOL; // returns 3, correct
print 'Result 2: ' . fubar2() . PHP_EOL; // returns 2, wrong and inconsistent with fubar1()
// Results
/*
Step 1: 1
Step 2: 2
Step 3: 2
Step 4: 3
Result 1: 3
Step 1: 1
Step 2: 2
Step 3: 2
Step 4: 3
Result 2: 2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment