Skip to content

how to Create Fluent Interfaces in PHP

We know that objects are always passed by reference, which means that we don’t need to return an object from a method in order to observe its changes. However, if we do return $this from a method, we can build a fluent interface into our application, which will enable you to chain methods together. It can be done following few steps : create an object, call a method on the object, and receive the amended object returned by the method.

The fluent interface usually we can found hmmmmm I remember on some  ORM classes/Active Record that has been adopted by many popular php frameworks.

example usage format :

As mentioned above the trick is simple, on each method that will be performed, just returns the resulting object, so we can then call the next method on that, and so on.

Let’s create a class file called myQuery.php

At the final steps, let’s create a file called index.php :

then compile the index.php  and the result should be like this :

the result

Oke, finish ^_^

It's only fair to share...Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0
Published inObject OrientedPHPProgrammingTips and Trik

Be First to Comment

Leave a Reply

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

× 4 = eight