Why return $this in setter methods?

后端 未结 2 1840
挽巷
挽巷 2021-01-01 16:06

Examining Zend Framework, I found that all setter methods (of those I’ve examined) return the instance of the class it lives in. It doesn\'t only set a value but also return

相关标签:
2条回答
  • 2021-01-01 16:41

    It's so that method calls on an object can be "chained", like this.

    $obj -> setFoo ('foo') -> setBar ('bar') -> setBaz ('baz') -> setFarble ('farble');
    
    0 讨论(0)
  • 2021-01-01 16:54

    The return $this allows the chaining of methods like:

    $foo->bar('something')->baz()->myproperty
    
    0 讨论(0)
提交回复
热议问题