Posts Tagged ‘oop’

Anonymous Classes

Saturday, November 19th, 2005

There have been some PHP6 wishlists in the recent past. I only have one wish: anonymous classes.

Someone who uses Java will know what anonymous classes are, but for those who don't, I will explain with examples.

Suppose we are dealing with buttons. We have a generic button class, that has an 'actionPerformed' method that is executed when the button is clicked. The generic implementation just echo's something when the button is clicked:

 
 
class Button
{
  ....
 
  function actionPerformed()
  {
    echo "The button was clicked";
  }
}
 
$form->add(new Button());

Now we want to use a button in an application, with custom behaviour when clicked. Let's assume we want to display the name of the form the button is located in when clicked. Currently In PHP we would have to do it like this:

 
 
  class CustomButton extends Button
  {
    var $m_form = NULL;
 
    function CustomButton(&$form)
    {
      $this->m_form = &$form;
    }
 
    function actionPerformed()
    {
      echo "The custom button in the ".$this->m_form->getTitle()." was clicked";
    }
  }
 
$form->add(new CustomButton($form));

This always requires the creation of an extra class. If PHP would support anonymous classes though, the code could look like this:

 
 
$form->add(new Button()
                 {
                   function actionPerformed()
                   {
                     echo "The custom button in the ".$form->getTitle()." was clicked";
                   }
                 });

What you basically do is create an instance of the Button class with a custom actionPerformed method appended to it. In essence this internally would create a nameless (hence 'anonymous') class that extends Button.

The advantage is that there's no need to create a new class for each button. Furthermore, this construct creates an 'inner anonymous class' that is in the same scope as the surrounding code, so the $form variable is directly accessible from the methods of the anonymous class.

This is also particularly useful when dealing with things like Listeners, which are used heavily in Java in conjunction with all sorts of design patterns (MVC, Observer, ActiveRecord etc). Example:

 
 
// Add a listener to perform some actions whenever a record is added.
$rowset->add(new RecordListener()
{
  function recordAdded()
  {
    refreshRecordCache();
    reloadPage();
  }
});

I hope PHP6 will feature this. In my opinion, it can be a very powerful OO technique.

I've tried to emulate this in PHP4/5 but so far have not found a solution that is easier than just creating new classes. Ideas are more than welcome.