Callbacks in PHP
function myExcitingFunction() {
// do something remarkable
}
call_user_func('myExcitingFunction');
You can also call methods of objects rather than just plain functions, and this is where I tripped myself up.
To do so, you pass an array with either the name of the class or an instantiated object as the first element in the array, and the name of the method as the second element. The (in hindsight, obvious) difference is that when you pass just the name of the class, the method is called statically (which is fine, as I wrote recently). If, on the other hand, you pass an instantiated object, the method gets called against the object. The distinction looks something like this:
class ObjectOfGreatUsefulness {
public function sparkle() {
// shiny awesome
}
}
// static call
call_user_func(array('ObjectOfGreatUsefulness', 'sparkle'));
// dynamic call
$sparklyThing = new ObjectOfGreatUsefulness();
call_user_func(array($sparklyThing, 'sparkle'));
Hopefully this makes it clear (for me at least!) how objects fit in with callbacks in general. You can also call relative classes, using for example the parent keyword, and closures – Read The Fine Manual page, as I failed to do, for more detail :)
Nice little post will definitely come in handy sometime in the future. :-D
Ah yes, I have used the static version of this to get round the problem of not having late static binding available in 5.2.
Worth mentioning that as of 5.3 the call_user_func_array also has support for namespaces.
Nice write-up. No worries about not RTFM…I think we all get bitten by that one every now and again :)
One additional note on what you can pass to call_user_func. You can also pass in an anonymous function, which is to say, you can pass in a lambda or closure.
I’ve introduced Gearman into a project I’m working on, and since a few people have asked I thought I’d share my experiences. Basically, this application generates some PDFs from a variety of data sources, makes images, and emails it. Since the whole dat
Thanks everyone for the nice comments and the additional points about what can be passed as a callback. The 5.3 features make this even more fun and interesting!
Thanks, all articles about callback is interesting for me!
Thanks for the guide Lorna. I wasn’t sure how to accomplish callbacks in PHP. I will give it a try.
Pingback: Programowanie w PHP » Blog Archive » Lorna Mitchell’s Blog: Callbacks in PHP
This is a very good article, I especially enjoyed the code
[code]
$sparklyThing = new ObjectOfGreatUsefulness();
call_user_func(array($sparklyThing, ‘sparkle’));
[/code]
Have you ever thought of / tried having callbacks registered with an object fulfilling the observer pattern? it can be used to provide application-wide events and object events. It becomes especially useful when combined with other design patterns.
Great , Thanks for your simple way