How to rewrite an example without the use of create_function?
Asked Answered
R

1

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?

Roadrunner answered 23/9, 2016 at 17:13 Comment(1)
its just $newfunc = function($a, $b){ return "ln($a) + ln($b) = " . log($a * $b);}Reiterate
G
9
$newfunc = function($a, $b) {
    return "ln($a) + ln($b) = " . log($a * $b);
}

echo $newfunc(2, M_E) . "\n";
Gracia answered 23/9, 2016 at 17:18 Comment(3)
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 differenceRoadrunner
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.Salas
Just in case someone is looking for the wordpress solution with create_function called in add_action... wordpress.org/support/topic/…Kitchener

© 2022 - 2024 — McMap. All rights reserved.