Dewan159
Dewan159

Reputation: 3074

how to do this in PHP OOP

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 ?

Upvotes: 4

Views: 92

Answers (2)

Edoardo Pirovano
Edoardo Pirovano

Reputation: 8334

I believe you can do this by returning the object at the end of the function. For example:

class GreetClass {
    function __construct($greeting) {
        $this->greeting = $greeting;
    }
    function a() {
        echo $this->greeting;
        return $this;
    }
    function b() {
        echo ' ';
        return $this;
    }
    function c($who) {
        echo $who;
    }
}
$obj = new GreetClass('Hello');
$obj->a()->b()->c('World'); // Echoes: Hello World

Upvotes: 2

Tim Fountain
Tim Fountain

Reputation: 33148

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;
    }
}

Upvotes: 7

Related Questions