O'Reilly logo

Zend PHP 5 Certification Study Guide by Ben Ramsey, Davey Shafik

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Closures and Callbacks

With each new version of PHP, more and more advanced features are added. One feature that can have a major impact on how you design code is Closures and callbacks.

Closures

PHP 5.3 added anonymous functions, otherwise known as Closures. Closures allow you to define anonymous functions that can be passed around as callbacks. Closures can be used as callbacks for any function that accepted traditional callbacks prior to 5.3, such as usort().

Closures are created simply by defining a function with no name, and assigning it to a variable:

$closure = function($who) {
    echo "Hello $who";
}

You then call a closure in the same way you would a regular function, using the variable instead of its name:

$closure("World"); // Hello ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required