Last active
March 28, 2016 18:11
-
-
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.
This file contains 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
<?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