Jump to content
Larry Ullman's Book Forums



Recommended Posts

Just like an array is traversable a closure is callable. The traversable part is why you can foreach an array, as foreach expects something implementing Traversable. You can actually implement Traversable directly on any object and foreach it directly.


The same principle applies to anonymous functions. It's just another type of structure PHP provides you with. Functions in PHP normally provides you encapsulation and execution of a set of logic. A closure is a reference to a function's definition, and behaves more like objects in PHP. When you have a closure, you can do stuff to it, just like you would an object.

// A reference to a callable function
$callable = function($text)
    echo $text;

// Perform an operation with a callable
$callable("I'm running now, guys!"); // Output happens here

call_user_func() and usort() are some of the functions that expects a callable. usort is probably the easiest to get.

// Define a normaly compare function
function compare($a, $
    if ($a == $ {
        return 0;
    return ($a < $ ? -1 : 1;

// Use the function normally
var_dump(compare(1, 1)); // Returns 0, they are equal

// Define an array to sort
$values = array(3, 1, 2);

// Sort the array using the "compare" function. This probably used call_user_func() 
// behind the scene to get a callable.
usort($values, "compare");

// So, let's do that directly instead
usort($values, function ($a, $ {
    if ($a == $ {
        return 0;
    return ($a < $ ? -1 : 1;

Hope that helps. 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...