Is returning $this from a setter wrong OOP POV (for setter chaining)?
class Person
{
protected $firstName, $lastName;
public function __construct($first = null, $last = null)
{
$this->firstName = $first;
$this->lastName = $last;
}
public function setFirstName($first)
{
$this->firstName = $first;
return $this;
}
public function setLastName($last)
{
$this->lastName = $last;
return $this;
}
}
$p = new Person();
$p->setFirstName('John')->setLastName('Smith');
I don’t thing it’s bad practice, Zend framework uses that (and I consider it great piece of php code which takes advantage almost of everything that php provides). Here’s a nice article with examples.
It allows you to write simplified code without repeated access to variables and better readable codes are what does matter..
Object are always (in php5) returned as references so it shouldn’t bring any overhead.
Anyway I would redeclare all functions to
public function &setFirstName($first)to make it explicit that you want to rewrite object itself in next call, but it’s definitely not necessary.EDIT on references
Here’s described what references are (read also what they do and what they aren’t) and how to return reference from function. As mentioned before, php 5 “works with object as reference by default” (not entirely true, read the article) so adding
&before function name isn’t necessary but you’ll make it clear (and explicit) that “I want to work with object reference”.