Closures in PHP… what, precisely, are they and when would you need to use them?

PHP will support closures natively in 5.3. A closure is good when you want a local function that’s only used for some small, specific purpose. The RFC for closures gives a good example:

function replace_spaces ($text) {
    $replacement = function ($matches) {
        return str_replace ($matches[1], ' ', ' ').' ';
    };
    return preg_replace_callback ('/( +) /', $replacement, $text);
}

This lets you define the replacement function locally inside replace_spaces(), so that it’s not:
1) cluttering up the global namespace
2) making people three years down the line wonder why there’s a function defined globally that’s only used inside one other function

It keeps things organized. Notice how the function itself has no name, it’s simply defined and assigned as a reference to $replacement.

But remember, you have to wait for PHP 5.3 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)