eAccelerator and PHP closures don’t mix

This post is more than 10 years old.

I struck an odd problem recently with some code using closures. I use closures extensively for WordPress filter and action hooks when building custom plugins and themes for websites, and all usually works well on any version of PHP from 5.3 up. But I was finding that my closures weren’t being called on some PHP 5.4 websites. The problem was eAccelerator.

Closures, also called anonymous functions, are a very convenient tool when writing callback functions. I use them a lot for things like array filters and WordPress action and filter hooks. They can reduce the amount of code, and put the solution right next to the the problem instead of many lines later in the code. (I don’t use them in published plugins yet, because there’s too many old servers still running PHP 5.2)

eAccelerator is a PHP opcode cache. It takes the compiled PHP code and caches it so that it doesn’t need to be compiled for each page request, thus reducing server load. It’s not the only one, but it’s been a solid faithful tool for many years and some hosting services still install it.

The problem is that eAccelerator has been slow to keep up with changes in the PHP language. Specifically, the version used by my client’s hosting company didn’t handle PHP 5.4 closures well, and especially closures that reference global variables. Oddly, it worked OK for PHP 5.3 closures, just not 5.4 closures.

The fix for my problem was simple: on the hosting account were I was loading websites, I disabled eAccelerator and enabled Zend’s opcache instead; opcache has kept up with PHP language developments and handles closures correctly. All good again!

If you are having strange problems with closures not working on a hosting environment with PHP 5.4 or greater, check for eAccelerator and replace it with opcache. You might need to ask your host to do this for you, as it may not be a configuration change you can make yourself.