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?


It's for chaining, e.g.


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.


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.