6.4. Object Methods as Callbacks
Prev | Chapter 6. Callbacks | Next

## 6.4. Object Methods as Callbacks

The callback function argument to SetCallback can be an array of two elements: a class variable and a method. This can be used with any class, but here we are interested in using an extension of the PHPlot class. Consider the following setup:

    class my_PHPlot extends PHPlot
    {
      function my_PHPlot($width=600, $height=400, $outfile=NULL, $infile=NULL)
      {
        $this->PHPlot($width, $height, $outfile, $infile);
      }

      function callback($img, $arg)
      {
        fwrite(STDERR, "callback in object\n");
        fwrite(STDERR, "Plot area: ({$this->plot_area[0]}, {$this->plot_area[1]}) :");
        fwrite(STDERR, " ({$this->plot_area[2]}, {$this->plot_area[2]})\n");
      }
    }

We define a class which extends PHPlot, and a method 'callback' which displays the plot area using the internal PHPlot class variable plot_area. (Note we are using a PHP4-style constructor, which also works with PHP5. You can use the PHP5 constructor method instead.)

We will then create an instance of the extended class, and set a callback.

    $plot = new my_PHPlot(400,300);
    $plot->SetCallback('draw_titles', array($plot, 'callback'));

This is for PHP5. For PHP4, you need to use a reference to the $plot instance. Note that PHP4 is no longer supported.

When the draw_titles callback is triggered, it will call the 'callback' method inside our extended class. Because this is an extension of the PHPlot class, it has access to all the member variables via $this.

Prev | Up | Next
6.3. Available Callbacks | Home | 6.5. Using Callbacks to Annotate Plots