Type Hinting Callable Functions in PHP

As of PHP 5.4, you can type hint your method arguments with the callable keyword allowing you to enforce the type of data that is passed via your arguments .

Let’s look at an example where we create a Sort class, with a custom method that takes a callable function so that we can customize how our data is sorted.

Example

<?php

class Sort
{
    public static function custom(array $data, callable $function)
    {
        usort($data, $function);

        return $data;
    }
}

Now let’s look at how we may use the above class to implement a sort on our array of data by ascending order.

<?php

$numbers = [
    10,
    5,
    9,
    4,
];

$numbersAscending = Sort::custom($numbers, function($number1, $number2) {
    return $number1 <=> $number2;
});

That’s all there is to it. Now we can pass any function as a second argument to our method allowing us to pass any custom sorting algorithm to our class.