-1

How do I convert another create_function. The one below

return create_function('$f,$e=null', "return ($parsed_tpl);");

to

$e=null;
return function($f,$e) { return ($parsed_tpl); };

or

return function($f,$e=null;) { return ($parsed_tpl); };

But neither of them are working.

I have tried everything above.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    Does this answer your question? [PHP 7.2 Function create\_function() is deprecated](https://stackoverflow.com/questions/48161526/php-7-2-function-create-function-is-deprecated). That answer shows the `use` part which you are missing – Chris Haas Dec 18 '22 at 16:32
  • 1
    @ChrisHaas The `use` statement is not the only problem here; the original function is using the fact that create_function was eval in disguise: https://3v4l.org/Y5Dib#v7.1.21 – IMSoP Dec 18 '22 at 22:33
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include your source code as a working [mcve], which can be tested by others. Please see: [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/q/284236). Please see: [What Do You Mean “It Doesn't Work”?](https://meta.stackexchange.com/q/147616) – Progman Dec 18 '22 at 22:37

1 Answers1

0

The key part to notice on the original code is this:

"return ($parsed_tpl);"

Note the double-quotes, meaning the variable will be expanded in the string before passing it to create_function. Then the expanded form will form the body of the function.

In other words, the actual code of the created function will be completely different every time - it won't just return the string, it will execute it as PHP code.

To achieve the same effect in current PHP, you need to use the eval function:

return eval("return ($parsed_tpl);");

You also have two mistakes in your attempt:

  • $e=null isn't an assignment, it's a default value for the parameter; it doesn't need a semicolon
  • You have to "capture" the $parsed_tpl variable with the use keyword to use it inside the function

The format is this:

$my_anonymous_function = 
    function($some_param, $next_param='default value', $another='another default')
    use ($something_captured, $something_else) {
        /* body of function using those 5 variables*/
    };
IMSoP
  • 89,526
  • 13
  • 117
  • 169