2

Possible Duplicate:
PHP method chaining?

So I can remember seeing in some code examples somewhere calling of a method on a method like:

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

Can you please explain to me what we call this, and give an example scenario of its usage? Also if you have a link to a tutorial or article on this would be helpful.

I'm new to Object Oriented PHP. And before you kill me for what might be a dumb question, understand that i don't know what to search for on Google, please help...

Community
  • 1
  • 1
Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58

2 Answers2

2

It's called Method chaining. Basically it's when a function or method, in this case method1(), returns an object and you call another method on this returned object.

A typical use of this is when a method returns the object itself. This can be useful because it makes calling lots of methods on the same object very simple. You can just type:

myobj.doSomething().doSomethingElse().jump();

One prominent example of this is the JavaScript library jQuery in which most methods return a jQuery object.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
2

It's called method chaining and it's simply the process of calling a method on the object returned by another method.

For example, method1 here returns an instance of some class that defined a method called method2, and so that method can be invoked immediately if you don't need the reference itself that method1 returned. It's essentially equivalent to this:

$temp = $object->method1();
$temp->method2();

It's particularly useful when you have several methods returning references to the instance they were called on. In this case, rather than writing this:

$object->method1();
$object->method2();
$object->method3();

you can write this:

$object->method1()->method2()->method3();
Will Vousden
  • 32,488
  • 9
  • 84
  • 95