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:

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

We could also do:

(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:

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 *

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