Method returns instance, after setting property

Asked

Viewed 41 times

2

There is a name for the practice or pattern, for this code snippet?

Example:

<?php

class Pessoa
{
   //...
   public setNome($nome)
   {
       $this->nome = $nome;
       return $this;
   }
   //...
}

1 answer

3


The question gives no details, but I believe it refers to the fact that the $this. This is used to create what is called interface Fluent (although not all cases are that). This way the methods can be chained to perform several operations in sequence with the object, since the result of each method is the received object itself which is then used as message for the next method.

This operation is called method chaining (this term can be used in this case regardless of how it is being used).

Apparently the style was created by Eric Evans and the term was coined by Martin Fowler.

There are many adherents and certainly there are advantages. But there are detractors and can be easily abused. I think it is used to compensate for language deficiency.

  • Our perfect guy. Thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.