user7780894
user7780894

Reputation:

Pass a function as parameter in 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
}

Upvotes: 3

Views: 136

Answers (1)

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

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";
});

Upvotes: 7

Related Questions