PHP Question: Print Object

28th April 2011

Question

The following code was executed.

  1. Which produced the following error.
  2.  
  3. Catchable fatal error: Object of class MyClass could not be converted to string in test.php on line 7
  4.  
  5. Call Stack:
  6. 0.0011 323736 1. {main}() /test.php:0
  7.  
  8. How can the code be simply changed to prevent this error and produce some form of result?
  9.  
  10.  
  11.  
  12.  
  13. Answer
  14. The easiest way to rewrite this code and to actually print out the object properly is to use the __toString() magic method. This method must return a string and is automatically called an object is printed out. The example code can therefore be rewritten like this:
  15.  
  16. foo;
  17. }
  18. }
  19.  
  20. $myObject = new MyClass();
  21. echo $myObject;
  22.  
  23. This stops the error occuring and will produce the output below.
  24.  
  25. bar
  26.  
  27. The __toString() function is useful for both debug purposes but also for decorating output. For example, we could have a User class that would print out the user's information, and a HtmlUser decorator class that prints out the user's information with surrounding HTML tags. This would be written like this:
  28.  
  29. _username = 'user1';
  30. $this->_forename = 'John';
  31. $this->_surname = 'Doe';
  32. $this->_created = time();
  33. }
  34.  
  35. public function __toString() {
  36. $output = '';
  37.  
  38. $output .= "Username = " . $this->_username . "\n";
  39. $output .= "Forename = " . $this->_forename . "\n";
  40. $output .= "Surname = " . $this->_surname . "\n";
  41. $output .= "Created = " . $this->_created . "\n";
  42.  
  43. return $output;
  44. }
  45.  
  46. }
  47.  
  48. class HtmlUser {
  49.  
  50. protected $user;
  51.  
  52. public function __construct(User $user) {
  53. $this->user = $user;
  54. }
  55.  
  56. public function __toString() {
  57. $output = "
    \n"; $output .= "\t
  • Username " . $this->user->_username . "
  • \n"; $output .= "\t
  • Forename " . $this->user->_forename . "
  • \n"; $output .= "\t
  • Surname " . $this->user->_surname . "
  • \n"; $output .= "\t
  • Created " . $this->user->_created . "
  • \n"; $output .= "
"; return $output; } } $user = new User(); $htmlUser = new HtmlUser($user); echo $htmlUser;

This produces the following output:

 
  • Username user1
  • Forename John
  • Surname Doe
  • Created 1304196043

Comments

Permalink

echo ( is_object( $myObject ) ) ? 'Sorry! We have an object here!' : $myObject ;

Anonymous (Thu, 04/28/2011 - 18:12)

Add new comment

The content of this field is kept private and will not be shown publicly.