Basic usage of a closure

suggest change

A closure is the PHP equivalent of an anonymous function, eg. a function that does not have a name. Even if that is technically not correct, the behavior of a closure remains the same as a function’s, with a few extra features.

A closure is nothing but an object of the Closure class which is created by declaring a function without a name. For example:

<?php

$myClosure = function() {
    echo 'Hello world!';
};

$myClosure(); // Shows "Hello world!"

Keep in mind that $myClosure is an instance of Closure so that you are aware of what you can truly do with it (cf. http://fr2.php.net/manual/en/class.closure.php )

The classic case you would need a Closure is when you have to give a callable to a function, for instance usort.

Here is an example where an array is sorted by the number of siblings of each person:

<?php

$data = [
    [
        'name' => 'John',
        'nbrOfSiblings' => 2,
    ],
    [
        'name' => 'Stan',
        'nbrOfSiblings' => 1,
    ],
    [
        'name' => 'Tom',
        'nbrOfSiblings' => 3,
    ]
];

usort($data, function($e1, $e2) {
    if ($e1['nbrOfSiblings'] == $e2['nbrOfSiblings']) {
        return 0;
    }
    
    return $e1['nbrOfSiblings'] < $e2['nbrOfSiblings'] ? -1 : 1;
});

var_dump($data); // Will show Stan first, then John and finally Tom

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents