Search code examples
phpphp-7.4

How to rewrite create_function into an arrow function in PHP


I have a simple code with create_funtion which I want to change in the anonymous arrow function.

$string = '3.2*2+1';
$compute = create_function("", "return (" . $string . ");" );
var_dump($compute());

How to extract logic from create_funtion to write it using an arrow notation?


Solution

  • With an arrow function $string will be available in the function scope:

    $compute = fn() => eval("return $string;");
    var_dump($compute());
    

    Or to use an argument:

    $compute = fn($s) => eval("return $s;");
    var_dump($compute($string));
    

    As with create_function:

    Caution This function internally performs an eval() and as such has the same security issues as eval(). Additionally it has bad performance and memory usage characteristics.

    If you are using PHP 5.3.0 or newer a native anonymous function should be used instead.

    The same cautions with eval:

    Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.