Score:2

Why do setter methods in an entity return $this?

cn flag

Writing a custom entity type I noticed that all setter methods in entity classes are returning $this after changes, as methods modify the object and so object will definitely being modified, then

what is the propose of returning the objects? is it a best practice?

Score:8
cn flag

It's for chaining, e.g.

$an_object
  ->doSomething()
  ->doSomethingElse()
  ->andSomethingElse();

Whether it's best practice is up for debate, there's no right or wrong answer to that. Some like it because it looks nice (so called fluent interface), some don't like it because, well because many reasons.

See https://stackoverflow.com/questions/1103985/method-chaining-why-is-it-a-good-practice-or-not for some interesting opinions.

Score:5
cn flag

The benefit is, you can chain methods, like saving the entity after you have set values:

$entity->set('label', 'foo')->save();

Caveat: save() doesn't return the object, but the result of the save operation as integer.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.