Method Chains PHP OOP

methods, oop, php

Solution

This is called Fluent Interface -- there is an example in PHP on that page.

The basic idea is that each method (that you want to be able to chain) of the class has to return `$this` -- which makes possible to call other methods of that same class on the returned `$this`.

And, of course, each method has access to the properties of the current instance of the class -- which means each method can "add some information" to the current instance.

Problem

Commonly, in a lot of frameworks, you can find examples of creating a query using the query builder. Often you will see: ``` $query->select('field'); $query->from('entity'); ``` However, in some frameworks you can also do it like this ``` $object->select('field') ->from('table') ->where( new Object_Evaluate('x') ) ->limit(1) ->order('x', 'ASC'); ``` How do you actually do this kinds of chains?

Original source