Using PHP Anonymous Functions In WordPress

Recently I published an article “Adding WordPress REST API Security To Basic CRUD Operations” where the permissions callback points directly to a function:

This style of defining a function call is known in PHP as an anonymous function.   The example is based on an example provided by the WordPress REST API documentation.   The problem with such a method is that it is not supported on older versions of PHP;  the anonymous function was introduced in PHP 5.3.  To exacerbate the problem, WordPress recommends PHP version 5.6 but will run on PHP version 5.2.4.    As such many hosting companies opt to take the path of least-effort and run the oldest version of PHP they can.  That means they are running PHP 5.2.4.

Guess what happens when a customer runs your plugin or theme that uses anonymous functions on PHP 5.2.4?  It breaks.

How do you fix the issue?

Use named functions.   Anywhere you use an anonymous function you can use a named function.    In the example above we can convert the anonymous function to a method within the class that is setting up our REST route:

 

Leave a Reply