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:

    register_rest_route( SLP_REST_SLUG . '/' . $version, '/locations/', array(
        'methods'               => WP_REST_Server::EDITABLE,
        'callback'              => array( $this, 'add_location' ) ,
        'permission_callback'   => function () { return current_user_can( 'manage_slp_user' ); } ,
        'args'                  => array(
            'sl_store'  => array( 'required'    => true ),
        )
    ) );

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:

class slp_rest_handler() {

function __construct() {
    register_rest_route( SLP_REST_SLUG . '/' . $version, '/locations/', array(
        'methods'               => WP_REST_Server::EDITABLE,
        'callback'              => array( $this, 'add_location' ) ,
        'permission_callback'   => array( $this, 'user_can_manage_slp' ) ,
        'args'                  => array(
            'sl_store'  => array( 'required'    => true ),
        )
    ) );
}

function user_can_manage_slp() { 
 return current_user_can( 'manage_slp_user' ); 
}

function add_location () {
}
}

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.