PHP

Comparing Objects

You can use the various comparison operators PHP makes available (== and ===) on objects, but their behavior is worth noting.

  • comparison operator (==) This works on objects by making sure that both objects are of the same type and have the same values for their member data. If either of these is not true, the operator evaluates to FALSE.

  • identity operator (===) This works on objects by indicating if the two objects being compared are the same instance of the class. Otherwise, it evaluates to FALSE.


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";
?>


by BrainBellupdated
Advertisement: