carlos
carlos

Reputation: 160

How to chain methods in PHP?

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!

Upvotes: 0

Views: 324

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

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.

Upvotes: 9

Related Questions