Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do this in PHP OOP

Tags:

oop

php

In Codeigniter, we can do :

$this->select('users')->orderBy('id')->limit(20)

I think this way of attaching methods to each other can work very good for me in my simple set of classes, but how to do it ?

like image 502
Dewan159 Avatar asked Jan 20 '23 09:01

Dewan159


1 Answers

This is called a fluent interface. To implement it, the function simply needs to return itself. Since the object is returned by reference, you can then chain together multiple calls:

class SomeClass
{
    public function select($table)
    {
        // do stuff

        return $this;
    }

    public function orderBy($order)
    {
        // do stuff

        return $this;
    }
}
like image 87
Tim Fountain Avatar answered Jan 28 '23 19:01

Tim Fountain