tags:

views:

80

answers:

3

Hello everybody!

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?

Thank you so much.

+4  A: 

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();
}
zombat
Damn, I knew it was possible. Was going to answer, but wanted to find some documentation to link to first, and didn't know what it was called exactly. Ah well, now I'll know for when I need to do this as well. Thanks.
Rob
Prior to 5.3 you can use `create_function`
Gordon
Thank you so much. Since I have to do it for PHP4.3 I guess I'll have to do what I want using another logic.
Cristian
@Casidiablo - See Jage's answer, you might be able to do something with `create_function()`. It's not quite the same, as you have to pass your function as a string of code, which then gets `eval()`'d behind the scenes. Not ideal, but you might be able to use it.
zombat
+2  A: 

You can also use create_function to create a function as a variable and pass it around. Though, I like the feeling of anonymous functions better. Go zombat.

Jage
+1 for the alternative. It sounds like the OP might need it.
zombat
+1  A: 

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.

webbiedave