Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 7.2 Function create_function() is deprecated

I have used create_function() in my application below.

$callbacks[$delimiter] = create_function('$matches', "return '$delimiter' . strtolower(\$matches[1]);");

But for PHP 7.2.0, create_function() is deprecated.

How do I rewrite my code above for PHP 7.2.0?

like image 442
Saly Avatar asked Jan 09 '18 04:01

Saly


People also ask

How to create new function in PHP?

Create a User Defined Function in PHP Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive. Tip: Give the function a name that reflects what the function does!


2 Answers

You should be able to use an Anonymous Function (aka Closure) with a call to the parent scoped $delimiter variable, like so:

$callbacks[$delimiter] = function($matches) use ($delimiter) {
    return $delimiter . strtolower($matches[1]);
};
like image 199
e_i_pi Avatar answered Oct 19 '22 21:10

e_i_pi


I would like to contribute with a very simple case I found in a Wordpress Theme and seems to work properly:

Having the following add_filter statement:

add_filter( 'option_page_capability_' . ot_options_id(), create_function( '$caps', "return '$caps';" ), 999 );

Replace it for:

add_filter( 'option_page_capability_' . ot_options_id(), function($caps) {return $caps;},999);

We can see the usage of function(), very typical function creation instead of a deprecated create_function() to create functions. Hope it helps.

like image 90
Joanmacat Avatar answered Oct 19 '22 21:10

Joanmacat