PHP

Tutorials and guides on PHP

Chaining setter methods in PHP

Written by: Peter Fisher on June 13, 2012
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
PHP Hypertext Preprocessor

PHP was called Personal Home Page before version 3.0. It is now a recursive acronym and stands for PHP Hypertext Preprocessor

How many times have you instantiated a PHP class and then set a bunch of properties using the class variable dare I ask? I thought so, well there is an easier way to do this, which in my opinion makes the code more readable and flexible.

Like jQuery, PHP can chain methods together as long as the method supplies the correct return value to subsequent chained methods. This feature was introduced in PHP5 as part or the OOP improvments over PHP4

So instead of the below:
[crayon lang=”php”]
$cat = new cat();
$cat->setName(‘Pixel’);
$cat->setType(‘tabby’);
$cat->setGender(‘female’);
$cat->setWhiskerCount(10);
$cat->setAge(1);
$cat->setWeight(5);
[/crayon]

You now have:
[crayon lang=”php”]
$cat = new cat();
$cat->setName(‘Pixel’)
->setType(‘tabby’)
->setGender(‘female’)
->setWhiskerCount(10)
->setAge(‘1 year’)
->setWeight(5);
[/crayon]

This works by returning the object in the setter methods like so:
[crayon lang=”php”]

class cat
{
private $_name;
private $_type;
private $_gender;
private $_whiskerCount;
private $_age;
private $_weight;

public function setName($name)
{
$this—>_name = $name;
return $this;
}

public function setType($type)
{
$this->_type = $type;
return $this;
}

public function setGender($gender = “male”)
{
$this->_gender = $gender;
return $this;
}

public function setWhiskerCount($whiskerCount = 0)
{
$this->_whiskerCount = $whiskerCount;
return $this;
}

public function setAge($age = 1)
{
$this->_age = $age;
return $this;
}

public function setWeight($weight = 1)
{
$this->_weight = $weight;
return $this;
}
}
[/crayon]

As you can see each setter method returns $this which allows subsequent methods to act upon the returned value.

In essence what you are doing is simply this:
[crayon lang=”php”]
$cat = new cat();
$cat->setName(‘Pixel’)->setType(‘tabby’)->setGender(‘female’)->setWhiskerCount(10)->setAge(‘1 year’)->setWeight(5);
[/crayon]

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Peter Fisher is a web developer working in Gloucester UK. Founder of the digital agency Websomatic, author of this blog and the HowToCodeWell Youtube channel. Peter has over ten years of web development experience under his belt

Read all about Peter Fisher

Leave a Reply

Your email address will not be published. Required fields are marked *