@ 2021-11-11T20:02:11Z <?php
function closure_to_str($func)
{
$refl = new \ReflectionFunction($func); // get reflection object
$path = $refl->getFileName(); // absolute path of php file
$begn = $refl->getStartLine(); // have to `-1` for array index
$endn = $refl->getEndLine();
$dlim = PHP_EOL;
$list = explode($dlim, file_get_contents($path)); // lines of php-file source
$list = array_slice($list, ($begn-1), ($endn-($begn-1))); // lines of closure definition
$last = (count($list)-1); // last line number
if((substr_count($list[0],'function')>1)|| (substr_count($list[0],'{')>1) || (substr_count($list[$last],'}')>1))
{ throw new \Exception("Too complex context definition in: `$path`. Check lines: $begn & $endn."); }
$list[0] = ('function'.explode('function',$list[0])[1]);
$list[$last] = (explode('}',$list[$last])[0].'}');
return implode($dlim,$list);
}
$test = 10;
$dog2 = function($var=0) use ($test){
$var = 10;
echo $var . PHP_EOL;
return $test . $var;
};
echo closure_to_str($dog2)."\n\n";
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 7.3.0 - 7.3.33 , 7.4.0 - 7.4.33 , 8.0.0 - 8.0.30 , 8.1.0 - 8.1.28 , 8.2.0 - 8.2.19 , 8.3.0 - 8.3.4 , 8.3.6 - 8.3.7 function($var=0) use ($test){
$var = 10;
echo $var . PHP_EOL;
return $test . $var;
}
Output for 8.3.5 Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
function($var=0) use ($test){
$var = 10;
echo $var . PHP_EOL;
return $test . $var;
}
preferences:dark mode live preview
106.95 ms | 402 KiB | 158 Q