Pass function as parameter in PHP

I saw people doing this:

usort($array, function() {
    //...
});

How to write a similar implementation using my own function? For instance,

runIt(function() {
     //...
});

and implementation runIt:

function runIt() {
    // do something with passed function
}
+4
source share
1 answer

function() {}is called an anonymous function and can be called using the parameter name. For instance,

function runIt($param) {
    $param();
}
runIt(function() {
    echo "Hello world!";
});

If you are interested in var-args, then:

function runIt() {
    foreach(func_get_args() as $param) {
        $param();
    }
}
runIt(function() {
    echo "hello world";
});
+7
source

Source: https://habr.com/ru/post/1695268/


All Articles