Duck Typing

I’m in fairly creative mood tonight, as evidenced by one (now two) blog postings, the PHP coding I did earlier, and the upload of some 75 random pictures to Facebook. I guess that’s what happens when I avoid the work I really should be doing. (Blech, JavaScript.)

Anyways, a few days ago a coworker mentioned something to me about duck typing, and I again decided to shirk my responsibilities and experiment. The basic idea is to stand typing on its head and have an imperative system rather than declarative — as they say, “if it walks like a duck, and quacks like a duck, it must be a duck.”

So how does that translate to actual code? Well, normally a class exports all its interfaces in a static list defined when the class is written. But sometimes it’d be nice to ask for a class that has all the features necessary to implement a given interface even if the class wasn’t declared as an implementor.

Since there’s no language support for this in PHP, my (proof-of-concept) solution relies exclusively on the Reflection library to validate method existence and signatures.

Time for an example.

class B
{
  public function woot($a)
  {
    echo 'haha';
  }
}

interface A
{
  public function woot($a);
}

var_dump(Goose::isA('A', new B()));

Notice that B never declares that it’s going to implement the interface A. Yet Goose::isA will return TRUE, because, while it’s not declared as such, B does satisfy all the requirements of the interface.

2 Comments so far

  1. andrew on August 9th, 2008

    As usual, I’ll defer to Wikipedia for a better explanation.

  2. Matt on August 9th, 2008

    And here I was, hoping for a story about you kidnapping some fowl from the park and training them on QWERTY. Or you purchasing a giant duck costume.

Leave a Reply