2

I'm trying to create a generic class in PHP that will provide a way to call a web service, parse the returning XML and return a JSON object.

I ran into fatal errors on servers that do not support CURL and/or JSON and looked for a way to gracefully returning the error in a JSON object back to the client, rather than crashing.
After some searching,I found an article that suggested I could call ob_start("fatal_error_handler") and provide a handler function:

function fatal_error_handler($buffer) {
    if (ereg("(error</b>:)(.+)(<br)", $buffer, $regs) ) {
        $err = preg_replace("/<.*?>/","",$regs[2]);
        $buffer = json_encode(array("errorMessage" => "Fatal error occurred", "exceptionMessage" => $err));
    }
    return $buffer;
} 

and calling ob_end_flush at the end of the script.
This worked well, but I now wanted to add that functionality to my class. I tried, and succeeded, in adding the following constructor and destructor:

    function __construct() {
        ob_start("fatal_error_handler");
    }

    function __destruct() {
        ob_end_flush();
    }

But when I tried moving the handler function into the class, there was no way I could add it to the ob_start() call. I tried ob_start("$this->fatal_error_handler"), and ob_start("WebService::fatal_error_handler") (WebService being my class name) - to no avail.

My question is, how do I pass a name of a class function to ob_start included in my constructor?

A bonus question: am I doing this right, or is there a a better way to handle fatal errors in a way that the client can handle?

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
  • You might be interested in this question, too: http://stackoverflow.com/questions/48947/how-do-i-implement-a-callback-in-php – soulmerge Sep 01 '09 at 12:17

1 Answers1

5
ob_start(array($this, 'fatal_error_handler'));
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • Thanks!!! This works, however, only if the handler function is marked as public (there's absolutely no output for protected or private). I wonder if there's any way around that? – Traveling Tech Guy Sep 01 '09 at 12:14
  • Not sure if this works but you can try passing $this by reference, ie: ob_start(array(&$this, 'fatal_error_handler')); – Alix Axel Sep 01 '09 at 12:42
  • 1
    @TTG: Since `fatal_error_handler` is called from outside the class, there's no way around it that respects visibility until PHP 5.3, when we get closures with our lambdas. Why is the error handler private/protected? – outis Sep 01 '09 at 13:27
  • I wanted it to be private (i.e, not accessible to the outside world), but now I have to keep it public :( – Traveling Tech Guy Sep 01 '09 at 13:35