title: PHP type hinting array of objects
body: <p>What would be the best way to check the type of an array in PHP?</p>
  
  <p>Lets say I have the following:</p>
  
  <pre><code>class Toggler
  {
  
      protected $devices;
  
      public function __construct(array $devices)
      {
          $this-&gt;devices = $devices;
      }
  
      public function toggleAll()
      {
          foreach ($this-&gt;devices as $device)
          {
              $device-&gt;toggle();
          }
      }
  
  }
  </code></pre>
  
  <p>What happens here is simple: The <code>Toggler</code> class requires an array of 'Devices', loops over those devices and calls the <code>toggle()</code> method on them.</p>
  
  <p>What I want however, is that the array of devices must contain only objects that implement the <code>Toggleable</code> interface (which would tell the object to supply a <code>toggle()</code> method).</p>
  
  <p>Now I can't do something like this, right?</p>
  
  <pre><code>class Toggler
  {
  
      protected $devices;
  
      public function __construct(Toggleable $devices)
      {
          $this-&gt;devices = $devices;
      }
  
      public function toggleAll()
      {
          foreach ($this-&gt;devices as $device)
          {
              $device-&gt;toggle();
          }
      }
  
  }
  </code></pre>
  
  <p>As far as I know you can't typehint an array as an array in PHP has no type (unlike languages like C++). </p>
  
  <p>Would you instead have to check type in the loop for each device? And throw an exception? What would be the best thing to do?</p>
  
  <pre><code>class Toggler
  {
  
      protected $devices;
  
      public function __construct(array $devices)
      {
          $this-&gt;devices = $devices;
      }
  
      public function toggleAll()
      {
          foreach ($this-&gt;devices as $device)
          {
              if (! $device instanceof Toggleable) {
                  throw new \Exception(get_class($device) . ' is not does implement the Toggleable interface.');
              }
  
              $device-&gt;toggle();
          }
      }
  
  }
  </code></pre>
  
  <p>Is there a better, cleaner, way to do this? I figured as I was writing this pseudo code you would also need to check if the device is an object at all (else you can't do <code>get_class($device)</code>).</p>
  
  <p>Any help would be appreciated.</p>