Catchable fatal error in PHP ... How to catch, and alternative solutions such as JSON
Archive - Originally posted on "The Horse's Mouth" - 2011-03-22 07:56:56 - Graham Ellis
When you ask your program to "print out an object", you're really looking to convert a data structure into a stream of characters, and it's not really obvious what you're looking to do.
If you try to print out an object in PHP: print ($result . "\n");
where the $result variable contains an instance of an object, you'll get a message like: Catchable fatal error: Object of class station could not be converted
to string in /Users/grahamellis/oop/oop5.php on line 108
How do you avoid your program failing like this? There are a number of options.
1. You can run a method on your object that will convert it to a string: print ($result->describe() . "\n");
2. You can serialize your object using the built in PHP serialise function. This will convert the object to s atring in predetermined format, so that you can unserialize it later ... and you'll get a string which you can save to file, print out, transmit to another computer, etc.
3. You can (from PHP 5.2) serialise the object with json_encode. "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate." ... [JSON intro ans spec]
The true return tells PHP that we're done with handling the error and it may proceed; the false return indicates that the error has not been (fully) handled by your handler and that the default one should also be called.
So .... 4 possible solutions - which is "best"? It's for you to decide the context. Overriding the error handler makes me worry - you're may be just masking a coding issue. Running a method (which you may need to write) on the object to present it in human-readable form is best for a production program. Serializing or json_encoding is best if you want to store the object, send it to another system, or print it out for analysis and debug purposes.
On yesterday's Object Oriented PHP Course, I developed an example during the day that showed many OO related features of PHP ... and some other features too, including the JSON and error_handler examples above. You can see then in full source code context [here].