phpfunctioncallable

How to write isEven() function as callable function?


I am learning PHP using reviewing some complete PHP projects. (I know that this is a bad way, but my goal is not to be a PHP programmer!) Anyway, I faced with the following function that is weird a little to me:

function filterIt($filter): callable {
    return function ($value) use ($filter) {
        return filter_var($value, $filter) !== false;
    };
}

I don't know what this function do and why it has been witter in such a way that a function is inside of another function! inner function returns something and main function also. Why we need such complicated function? or maybe one can make it simpler?

For this reason I want to write isEven() function as callable function like above. But I have no idea!

I don't know what that function do, but by mimicking from that:

function isEven($num): callable {
    return function () use ($num) {
        return $num % 2 == 0;
    };
}

I couldn't debug this using var_dump or print_r .


Solution

  • Not sure how you are calling this in you're test, but as the function is actually returning a callable you would be able to debug it once you run it like this:

    <?php
    
    function isEven($num): callable {
        return function () use ($num) {
            return $num % 2 == 0;
        };
    }
    
    var_dump(isEven(14)());