About

Andrew Culver, an inexperienced software engineer, vents opinions of questionable value on PHP and software development while inviting rebuke from strangers.

Are you familiar with method chaining? If not, the concept is very simple and you should at least understand enough to recognize when it’s being used. Consider the following example:

  1. $select = new Select();
  2. $select->columns(‘id, name’)->from(‘person’)->where(‘age > 25′);

Why? The purpose of the class author is to provide a fluid syntax and flexible interface for configuring an object.

How? None of these methods would have previously returned any meaningful information about the operation performed, so the class author has returned $this instead. By returning $this, any additional method call will continue to target the same object. You can also use regular methods that do return meaningful information in a method chain, but they terminate the chain by returning something other than $this.

What I haven’t covered in this extremely brief introduction are the design considerations that exist when designing a class that provides chaining syntax. Why not make all mutator methods support method chaining (ie. $person->setName('Andrew')->setAge(25);)? That belongs to a group of more involved topics which have been covered elsewhere.

Leave a Reply

You must be logged in to post a comment.