Accept function as parameter in PHP

I've been wondering whether is possible or not to pass a function as parameter in PHP; I want something like when you're programming in JS:

object.exampleMethod(function(){
    // some stuff to execute
});

What I want is to execute that function somewhere in exampleMethod. Is that possible in PHP?


Solution 1:

It's possible if you are using PHP 5.3.0 or higher.

See Anonymous Functions in the manual.

In your case, you would define exampleMethod like this:

function exampleMethod($anonFunc) {
    //execute anonymous function
    $anonFunc();
}

Solution 2:

Just to add to the others, you can pass a function name:

function someFunc($a)
{
    echo $a;
}

function callFunc($name)
{
    $name('funky!');
}

callFunc('someFunc');

This will work in PHP4.