Over a million developers have joined DZone.

Callbacks in PHP

DZone's Guide to

Callbacks in PHP

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


Published at DZone with permission of Lorna Mitchell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}