Method returns instance after definition of property [duplicate]

2

Is there a name for the practice or pattern for this code snippet?

Example:

<?php

class Pessoa
{
   //...
   public setNome($nome)
   {
       $this->nome = $nome;
       return $this;
   }
   //...
}
    
asked by anonymous 13.08.2016 / 19:13

1 answer

3

The question does not give details, but I believe it refers to the fact that it returns $this . This is used to create what is called fluent interface (although not all cases are the same ). In this way the methods can be chained to perform several operations in sequence with the object, since the result of each method is the object itself that 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 to parse is being used).

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

There are many supporters and there are certainly advantages. But there are detractors and can be easily abused.

    
13.08.2016 / 19:42