3v4l.org

run code in 300+ PHP versions simultaneously
<?php class TestClass { function getClosure() { return function () { var_dump($this); } } } $abc = "testABC"; $xyz = new TestClass(); $test = true; $x = function () use ($test, $xyz, $abc) { echo $abc; var_dump($test, $xyz); var_dump($this); }; $test = new TestClass(); echo packAnonFunction($x, $test, $xyz, $abc); echo packAnonFunction($test->getClosure()); 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; }
Output for 7.0.0
Parse error: syntax error, unexpected '}', expecting ';' in /in/anF8Y on line 7
Process exited with code 255.
Output for 5.5.24 - 5.5.30, 5.6.8 - 5.6.16
Parse error: syntax error, unexpected '}' in /in/anF8Y on line 7
Process exited with code 255.

preferences:
175.84 ms | 1395 KiB | 24 Q