[Previous] [Contents] [Next]


User-Friendly Output

Normally, when you call print or echo with an object, you get output similar to the following:

Object id #5

This is largely unhelpful and tells us little about the object. However, I do not always want to use var_dump, print_r, or var_export, since they can be entirely too detailed for my needs.

To get around this, PHP allows us to define a method called __toString on my classes to call the print and echo functions. I can use this to represent the object as I would like and help ourselves with debugging.

<?php

  class Product implements IProduct
  {
    // etc.

    public function __toString()
    {
      return get_class($this) . ", Name: " . $this->get_Name()
             . ", Price: " . $this->get_PricePerUnit()
             . "<br/>\n";
    }

    // etc.
  }

?>

The only caveat to using this function is that it is only called when your class is the sole item passed to a print or echo call.

<?php

   $prod = new LocalProduct("1-02-11", "Master Fishin' Pole",
                            "Master Fishin' Poles are the ...",
                            12.99);
   //
   // this will print:
   // "LocalProduct: Name = Master Fishin' Pole, Price: 12.99"
   //
   echo $prod;

   //
   // this will print:
   // "About this product: Object id #3<br/>\n"
   //
   echo "About this product: " . $prod . "<br/>\n";

?>


[Previous] [Contents] [Next]