views:

83

answers:

2

Possible Duplicate:
How to build multi oop functions in PHP5

Hey,

I've seen this kind of code in a couple of forum systems but I can't find any examples like this:

$this->function()->anotherfunction();

You can see a similar example in PDO:

$pdo->query($sqlQuery)->fetch();

I don't know how this type of coding is called in PHP and thus I can't get on looking for any tutorials and examples. Could you please give me a hint where and what should I look for?

I'd appreciate any help on this :)

Thanks in advance,
The devil

+7  A: 

This is called method chaining. An example would be the following. Notice we are returning the current object.

class Example
{
   function test1($var)
   {
      return $this;
   }
   function test2($var)
   {
      return $this;
   }
}

$obj = new Example();
$obj->test1('Var')->test2(543)->test1(true);
Tim Cooper
Thanks for sharing this valuable information :)
The Devil
+2  A: 

You just make sure a chainable method returns an object reference, and you can chain another method call onto the result.

You can return $this as @Tim Cooper shows, or you can return a reference to another different object:

class Hand
{
  protected $numFingers = 5;
  public function countFingers() { return $this->numFingers; }
}

class Arm
{
  protected $hand;
  public function getHand() { return $this->hand; }
}

$n = $body->getLeftArm()    // returns object of type Arm
          ->getHand()       // returns object of type Hand 
          ->countFingers(); // returns integer

The PDO example you show uses two different object types. PDO::query() instantiates and returns a PDOStatement object, which in turn has a fetch() method.

This technique can also be used for a fluent interface, particularly when implementing an interface for domain-specific language. Not all method chains are fluent interfaces, though.

See what Martin Fowler wrote about fluent interfaces in 2005. He cites Eric Evans of Domain-Driven Design fame as having come up with the idea.

Bill Karwin
...and being a programmer, having your fingers protected is important for your livelihood ;)
Wrikken
This explains pretty much everything I had to know. Thank you :)
The Devil