-1

just learning PHP and I have a project I'm looking at which appears to have typos but I'm not sure if they are or not.

I want to know if the output of the two bits of code below is the same.

  $this->addSubmitElement($this->_buttons[self::BTN_LIST], self::BTN_LIST);
  $this->addSubmitElement($this->_buttons[self::BTN_DRAFT], self::BTN_DRAFT);

and

  $this->addSubmitElement($this->_buttons[self::BTN_LIST], self::BTN_LIST)
   ->addSubmitElement($this->_buttons[self::BTN_DRAFT], self::BTN_DRAFT);

It seems it should be but my project behaves differently depending on which version I have.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
Ashlin
  • 1
  • If your project behaves differently then it's not the same. Second code is an example of method chaining: https://en.wikipedia.org/wiki/Method_chaining – Jsowa Oct 10 '20 at 21:43
  • The first example returns two values (one for each line). The second example returns a single value (because the `addSubmitElement` method is _chained_). So they are not the same. – Jeroen van der Laan Oct 10 '20 at 21:44
  • Related: https://stackoverflow.com/questions/3724112/php-method-chaining – raina77ow Oct 10 '20 at 21:50
  • If the return value of `addSubmitElement()` is `$this`, then yes, they do the same – Cid Oct 10 '20 at 21:54
  • Thanks all, I understand better now. I felt Jeroen's answer was the most clear. I'll look into method chaining some more. – Ashlin Oct 12 '20 at 03:42

1 Answers1

0

There's a common pattern used when designing 'mutating' methods (setSmth, addSmth) that update some properties of an object: use that object (i.e., $this) as return value.

Following this pattern enables chaining you've showed in your second example. Note that this is a pattern, but not a requirement; if the package changed, you're not able to use that approach anymore.

raina77ow
  • 103,633
  • 15
  • 192
  • 229