phppatchcreate-function

Patch for create_function() causes problems in PHP 7.3.6


I am trying to replace deprecated "create_function" in a CMS. I already found a lot of answers for this topic. However, the patch I used resulted in even more trouble and I am not really firm in working on this level of PHP functions. Therefore I would be really happy, if someone could help me out here.

I changed

$list->setColumnFormat('active', 'custom', create_function(
  '$params',
  'global $I18N;
   $list = $params["list"];
   return $list->getValue("active") == 1 ? $I18N->msg("yes") : $I18N->msg("no");'
));

to

$list->setColumnFormat('active', 'custom', function($params) {
  global $I18N; 
  $list = $params["list"]; 
  return $list->getValue("active") == 1 ? $I18N->msg("yes") : $I18N->msg("no");
});

However then - instead of just a "deprecated" message - I get

Recoverable fatal error: Object of class Closure could not be converted to string in [filename] on line 155

line 155 is:

trigger_error('rexCallFunc: Using of an unexpected function var "'.$function.'"!');

var_dump($function) gives:

object(Closure)#16 (1) { ["parameter"]=> array(1) { ["$params"]=> string(10) "" } }

If I comment this line 155 out, I also get:

Warning: call_user_func() expects parameter 1 to be a valid callback, function '' not found or invalid function name in [the same filename] on line 163

line 163 is:

return call_user_func($func, $params);

var_dump($func) gives:

string(0) "" 

Does anybody have an idea what this is about and how it can be solved?


Solution

  • create_function returns a string with the name of an "anonymous" function, not an anonymous function. If you want to avoid changing the setColumnFormat() method, you'll need to create a named function rather than an anonymous function, and pass that name as a string that setColumnFormat() can use in call_user_func().

    function patchFunction($params) {
        global $I18N; 
        $list = $params["list"]; 
        return $list->getValue("active") == 1 ? $I18N->msg("yes") : $I18N->msg("no");
    }
    
    $list->setColumnFormat('active', 'custom', 'patchFunction');