Constraining Arguments to Methods with Hints

In PHP 4, and most of the time in PHP 5, you have to rely on type-checking code and naming conventions to signal the argument types your methods expect. This generally suffices but can lead to error-prone code when the wrong data type is passed to the wrong argument variable.

Let’s create a method that collects Item objects to illustrate some of the dangers that a relaxed attitude toward type can bring:

class ItemLister {
  private $items = array();

  function addItem( $item ) {
    array_push( $this->items, $item );
  }

  function splurgeItems () {
    foreach( $this->items as $item ) {
      print $item->getProductString ();
      print "<br />";
    }
  }
 }

The ItemLister class is very simple indeed. It uses the addItem() method ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.