Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite an example without the use of create_function?

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?

like image 258
Dennis Avatar asked Sep 23 '16 17:09

Dennis


People also ask

How many parameters create_ function() takes?

The create_function() is an inbuilt function in PHP which is used to create an anonymous (lambda-style) function in the PHP. Parameters: This function accepts two parameters which is describes below: $args: It is a string type function argument.

What is an anonymous function in PHP?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.


1 Answers

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

echo $newfunc(2, M_E) . "\n";
like image 151
Zoli Szabó Avatar answered Oct 05 '22 11:10

Zoli Szabó