6

When looking at PHP's create_function it says:

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

I want to recreate same functionality of create_function but using an anonymous function. I do not see how, or if I am approaching it correctly.

In essence, how do I change the following so that I no longer use create_function but still can enter free-form formula that I want to be evaluated with my own parameters?

$newfunc = create_function(
    '$a,$b',
    'return "ln($a) + ln($b) = " . log($a * $b);'
);
echo $newfunc(2, M_E) . "\n";

Example taken from PHP's create_function page.

Note:

It looks like with the above example I can pass in an arbitrary string, and have it be compiled for me. Can I somehow do this without the use of create_function?

Dennis
  • 7,907
  • 11
  • 65
  • 115

1 Answers1

9
$newfunc = function($a, $b) {
    return "ln($a) + ln($b) = " . log($a * $b);
}

echo $newfunc(2, M_E) . "\n";
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19
  • 1
    oh wait ... it make sense but I also see that `functionality` is different. In the original example, `log($a * $b)` is *not* hardcoded, it can be passed as a string. With anonymous function, that feature is lost. You have to hardcode the `log` function. It cannot be changed "on the fly. I guess that's the difference – Dennis Sep 23 '16 at 19:19
  • 1
    For that use case, you are right. If you want to build functions with dynamic bodies, you should stick with create_function. Anonymous functions are meant to replace the create_function in other cases, like callbacks. – Zoli Szabó Sep 23 '16 at 19:38
  • Just in case someone is looking for the wordpress solution with create_function called in add_action... https://wordpress.org/support/topic/bug-php-7-create_function-is-deprecated/ – Ricardo Martins Apr 24 '20 at 03:28