Question

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?

Was it helpful?

Solution

ob_start(array($this, 'fatal_error_handler'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top