Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Jonathon

Closures

Recommended Posts

Hi Larry
 
In any of your PHP writings do you have anything on closures. I feel like you do in the JavaScript book. I'll have to have a look, but just wondering could you with your expert ability to explain things explain a closure.

 

Thanks

 

Jonathon

Share this post


Link to post
Share on other sites

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. 

Share this post


Link to post
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.

Guest
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.

Loading...
Sign in to follow this  

×
×
  • Create New...