views:

177

answers:

1

I recently really wanted to us anonymous functions in PHP. Unfortunately my host is still on 5.2. I automatically thought this would work:

uasort($array, function($a, $b) {
    return $a > $b;
});

Is this how they work? Simply passed in as an argument instead of a callback? The docs don't say specifically that's how they do, but I have a working knowledge of JavaScript's anonymous functions, so I assumed they would.

A: 

Yes. You can use it in place of regular PHP callbacks.

Try this (in PHP 5.3):

function wait($callback)
{
    sleep(10);
    call_user_func($callback);
}

wait(function(){
    echo "Hello!";
});

How call_user_func() works is it will accept any of the following:

'functionName'
array('className', 'methodName')
array($objectInstance, 'methodName');

and now in PHP 5.3

function(){ // .. do something .. 
}

My guess is that internal PHP functions user call_user_func() for callbacks, and because it has support for anonymous functions, they will work just as well as other callbacks.

Chacha102
Thanks for your answer. Just wondering, what are the practical uses of `sleep()`?
alex
If you want to limit how many things happen per set time. In example, Twitter only provides 150 calls per hour. I might `sleep()` between calls in a loop to make sure I don't hit 150 calls in an hour.
Chacha102
Ah, thanks. I've just always used server side caching for things like that.
alex
I mean in a cronjob, when a script is running continuously. Like I am searching for my name and adding the data to a database. I can have script always running, and limit the calls.
Chacha102
I just read the docs from the beginning and it *does* say you can use them as callbacks. Whoops.
alex
Why the downvote?
alex