0

I have a question about how is the best way to realize it.

class name {
  public function method($a){ 
    $this->a = $a; 
  }
  public function two($b){
    $this->b = $b;
  }
}

How I call $class->method('a')->two('b'); ?

return __CLASS__; // self?

on every method? or what? idk what is the best way or how all frameworks realize it.

If anyone can guide me I'll be very greatful... thanks!

dbf
  • 3,278
  • 1
  • 24
  • 34
carlos
  • 140
  • 1
  • 12

1 Answers1

9

It's done by returning $this in every method.

class name {
  public function method($a){ 
    $this->a = $a;
    return $this; 
  }
  public function two($b){
    $this->b = $b;
    return $this; 
  }
}

Anyway there are many opponents (including me) of this convention for a few reasons.

jeroen
  • 91,079
  • 21
  • 114
  • 132
Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
  • 2
    I'm curious as to what your reasons against this convention are. Personally I've been using this convention since my C++ days. – apokryfos May 13 '16 at 12:57
  • Search for "method chaining". There's a lot of discussion on the Internet. Here an example: http://stackoverflow.com/questions/16976150/benefits-and-drawbacks-of-method-chaining-and-a-possibility-to-replace-all-void – Jakub Matczak May 13 '16 at 13:03