3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php class TestClass { } $abc = "testABC"; $xyz = new TestClass(); $test = true; $x = function () use ($test, $xyz, $abc) { echo $abc; var_dump($test, $xyz); var_dump($this); }; $x->bindTo(new TestClass, "TestClass"); $x(); echo packAnonFunction($x, $test, $xyz, $abc); function packAnonFunction($payload, ...$args) { $func = new ReflectionFunction($payload); $filename = $func->getFileName(); $start_line = $func->getStartLine() - 1; $end_line = $func->getEndLine(); $length = $end_line - $start_line; var_dump($func->getClosureThis()); $source = file($filename); $body = implode("", array_slice($source, $start_line, $length)); $body = preg_replace('/(?:(?:(\$[a-z]+)\s\=)|return)\sfunction/', '\\$payload = function', $body); if(preg_match('/use\s\((\$[a-zA-Z0-9]+(?:,\s\$[a-zA-Z0-9]+)*)\)/', $body, $matches)) { $vars = $matches[1]; if(strpos($vars, ', ') !== false) { $parts = explode(', ', $vars); } else { $parts = [$vars]; } $body = str_replace(" use (" . $vars . ")", "", $body); } else { $parts = []; } if(strpos($body, '$this') !== false) { $parts[] = '$this'; $args[count($parts) - 1] = $func->getClosureThis(); } $return = []; foreach($parts as $key => $variable) { $return[$variable] = $args[$key]; } $variableString = ""; foreach($return as $var => $value) { $value = serialize($value); $variableString .= "\t{$var} = unserialize('{$value}');\n"; } $body = str_replace("{\n", "{\n" . $variableString, $body); return $body; }
based on ahYe2
Output for 7.1.0 - 7.2.0
testABCbool(true) object(TestClass)#1 (0) { } Fatal error: Uncaught Error: Using $this when not in object context in /in/0RroH:11 Stack trace: #0 /in/0RroH(15): {closure}() #1 {main} thrown in /in/0RroH on line 11
Process exited with code 255.
Output for 5.6.8 - 7.0.20
testABCbool(true) object(TestClass)#1 (0) { } Notice: Undefined variable: this in /in/0RroH on line 11 NULL NULL $payload = function () { $test = unserialize('b:1;'); $xyz = unserialize('O:9:"TestClass":0:{}'); $abc = unserialize('s:7:"testABC";'); $this = unserialize('N;'); echo $abc; var_dump($test, $xyz); var_dump($this); };
Output for 5.4.10 - 5.5.35
Parse error: syntax error, unexpected '.', expecting '&' or variable (T_VARIABLE) in /in/0RroH on line 18
Process exited with code 255.
Output for 5.3.20 - 5.3.29
Parse error: syntax error, unexpected '.', expecting '&' or T_VARIABLE in /in/0RroH on line 18
Process exited with code 255.