Edit Eclipse Generate Getter and Setters Format

For me, I like to always return $this when creating a setter class method when coding PHP.

For example, to set an object to be freaky, I would create method like this.

/**
 * Set to freaky or not freaky.
 *
 * @param boolean $freaky
 * @return $this
 */
public function setFreaky($freaky) 
{
    $freaky === TRUE ? $this->freaky = TRUE : $this->freaky = FALSE;
    return $this;
}

Then if I had a method to set an object’s hair color, I could have a method like this.

/**
 * Set hair color
 *
 * @param string $color
 * @return $this
 */
public function setHairColor($color) 
{
    $this->color = $color;
    return $this;
}

Now if I can chain these method calls.

$dreamPartner = new Partner();
$dreamPartner->setFreaky(TRUE)->setHairColor('#FF3333');

Not everyone may prefer this technique, but I like it better than.

$dreamPartner = new Partner()
$dreamPartner->setFreaky(FALSE);
$dreamPartner->setHairColor('#FFF5DD');

There’s no right or wrong answer, but returning $this in setters, gives the programmer using the class the option of chaining method calls. There’s no downside to doing this.

If you’re using Eclipse, you can modify the “Generate Getters and Setters” formatting for PHP under Preferences. Look for PHP -> Code Style -> Code Templates. On the Code Templates screen, expand Code and select Setter Body.

Double-click Setter Body and it should look like this.

${field} = ${param};

I changed it to look like this.

${field} = ${param};
return $$this;
Share Button