Chaining in OOP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • smartic
    New Member
    • May 2007
    • 150

    Chaining in OOP

    while i try to learn Zend framework i saw this code:
    Code:
    $this->addDecorator('FormElements')->addDecorator('HtmlTag', array('tag' => 'dl'))->addDecorator('Fieldset')->addDecorator('DtDdWrapper');
    I'm new in OOP, i need an example to do something like that.
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #2
    Can you clarify your question please?

    Comment

    • pbmods
      Recognized Expert Expert
      • Apr 2007
      • 5821

      #3
      Heya, Smartic.

      You're probably talking about chaining (which falls under a programming style known as Fluent Interface).

      When you want to implement chaining, you simply need to make sure that each method call returns a reference to its parent instance by using the $this keyword:

      [code=php]
      class Foo
      {
      public function bar( )
      {
      return $this;
      }

      public function baz( )
      {
      return $this;
      }
      }

      $Foo = new Foo();
      $Foo->bar()->baz();
      [/code]

      PHP does not allow you to chain off of the constructor, so you have to initialize (in this case) the Foo instance in a separate statement.

      Note that $Foo->bar() returns a reference to $Foo, which allows you to chain the subsequent call to baz(). It would be equivalent to writing this:

      [code=php]
      $Foo = new Foo();
      $Foo->bar();
      $Foo->baz();
      [/code]

      Comment

      • smartic
        New Member
        • May 2007
        • 150

        #4
        thank you pbmods

        Comment

        Working...