Why I love anonymous functions in PHP 5.3+ for WordPress functions.php

David Nash php, wordpress Leave a Comment

From PHP 5.3, we can now use anonymous functions. If you write jQuery javascript, you probably use these all the time, even if you’re not aware of it:

[js] jQuery(document).ready(function($) { //… });
[/js]

Here we’re calling the ready function and passing it an anonymous function.

We could also do:

[js] function do_stuff() {
//…
}

jQuery(document).ready(do_stuff);
[/js]

(Let’s ignore the “$” for now).

It’s the same with PHP. We don’t have to name functions – they can be anonymous.

Why do I love it for WordPress? Adding actions and filters always seemed so clunky. We write a do_my_thing() function and then call add_action(), passing the hook and the function name. The code wasn’t nicely contained. But with anonymous functions it’s all nice and neat again, and I think easier to read. For example:

[php] //functions.php
// load theme javascript
add_action(‘wp_enqueue_scripts’, function() {
wp_enqueue_script(‘moment’, get_stylesheet_directory_uri().’/js/moment.min.js’, array(‘jquery’), ‘1.0’, true);
wp_enqueue_script(‘inthenow’, get_stylesheet_directory_uri().’/js/theme.js’, array(‘jquery’, ‘moment’), ‘1.0’, true);
});
[/php]

Isn’t that easier to read? It’s easier to write too. Give it a try!

Leave a Reply

Your email address will not be published. Required fields are marked *