Over a million developers have joined DZone.

Callbacks in PHP

DZone 's Guide to

Callbacks in PHP

· Web Dev Zone ·
Free Resource
Recently I was working on something and I wanted to call an object method as a callback, but got confused when I realised the method had been caused statically. This was caused by my inability to RTFM and I wondered how I'd come so far without actually coming across the many and varied things you can pass into any place a callback is needed. I think we've all seen a function callback; something like this:

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 :)

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}