views:

51

answers:

4

I've seen other objects that do this:

$obj->method1()->method2();

How do I do that? Is each function just modifying the pointer of an object or returning a pointer?

I don't know the proper term for this style -- if anyone could help me with that, it would be great.

+4  A: 

Fluid interface.

Simply set your object's method1() to return $this

Mark Baker
+4  A: 

This is achieved by returning $this at the end of each function, thus giving a chainable reference.

class MyClass {
    public function method1() {
        //...
        return $this;
    }
    public function method2() {
        //...
        return $this;
    }
}
Lotus Notes
In the same way, if I return another object, it can also be chained? In my specific case I'm returning a MySQLi prepared statement, which I suppose I could then immediately do a bind_param on?
Kerry
Yes. Just keep in mind that having a lot of different objects being returned in a chain can make your API quite confusing to use. It might be worth typing in the extra line instead of transferring the chain to another object.
Lotus Notes
Totally understood thanks! :)
Kerry
+1  A: 

Lets say you have a Person class. You will have your methods doing something like that:

public function setName($name)
{
    $this->name = $name;
    return $this; // We now return $this (the Person)
}

Download Zend Framework and check some part of the code - you can learn a lot from there.

Ronaldo Junior
A: 

I refer to this as method chaining. See http://www.devshed.com/c/a/PHP/Method-Chaining-in-PHP-5/1/

also inside your method

public function method1()
   // do stuff

   return $this;
}
dalton