0

Possible Duplicate:
PHP method chaining?

In a lot of APIs I've worked with, I've seen this sort of thing:

$object->method()->anotherMethod();

From the tutorials on OOP that I've read, this is how classes are written,

<?php
class myClass {
    public method() {
       // do something
    }
}
?>

When should this be used, and how can it be done? Apologies, but I am new to OOP.

Community
  • 1
  • 1
Jared
  • 396
  • 4
  • 14
  • 1
    the method isn't an object, it returns an object (usually the same object as the first one) and the second method is called on that object – Esailija May 27 '12 at 12:51
  • Is it possible to make it return another object? eg In the APIs I've used, the methods in $object are different to those in $object->method(). EDIT: You could use 'return new class();'? – Jared May 27 '12 at 12:56
  • more http://stackoverflow.com/search?q=method+chaining – Gordon May 27 '12 at 13:02
  • also https://secure.wikimedia.org/wikipedia/en/wiki/Law_of_Demeter – Gordon May 27 '12 at 13:08

2 Answers2

4

If your method returns $this, you will be able to use the above style ($object->method()->anotherMethod()). This can be done only in cases where your method is not expected to return something else, e.g. a method named like getSomething() is expected to return Something, but if you have a method that has no relevant value to return, you can just return $this, allowing method call chains.

lanzz
  • 42,060
  • 10
  • 89
  • 98
3

This is called Method Call Chaining. There are no hard and fast rules about when you should use it, but the general rule I use is that method chaining makes sense when there are a series of object methods that are frequently called one after the other, such as initialization functions.

Chris Hayden
  • 1,104
  • 6
  • 6