Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a function as parameter in PHP

Tags:

php

I have seen people doing this:

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

How can I write similar implementation using my own function? For eg:

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

and implementation of runIt:

function runIt() {
    // do something with passed function
}

1 Answers

function() {} is called anonymous function and can be invoked using the param name. For eg:

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";
});
like image 85
Aniket Sahrawat Avatar answered Jun 02 '26 06:06

Aniket Sahrawat