0

I see in codeigniter a sintaxis method->other_method->other_method_again. example:

$this->db->select()->join()->findAll();

When i try

class MyClass{
       public function bla(){
             echo "bla";
       }
       public function other(){
             echo "other";
       }
}

$message = new MyClass();

$message->bla()->other();

Return:

Fatal error: Call to a member function other()

as I can do what codeigniter?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Abel Olguin Chavez
  • 1,350
  • 1
  • 12
  • 24
  • Spend 10 minutes writing an informative answer with examples for it to be closed. Makes me not want to answer on SO. – Torra May 31 '15 at 20:05
  • @Torra sometimes it is good to post a tentative answer first and then edit it or improve it afterwards – Nikos M. May 31 '15 at 22:48
  • I apologize, but I do not speak English and never (never) found something similar to what I was looking on page ok? – Abel Olguin Chavez Jun 01 '15 at 03:44

1 Answers1

1

this is called method chaining (popularised by jQuery chaining) and is achieved if you

return $this

from each method

for your example:

class MyClass{
       public function bla(){
             echo "bla";
             return $this; // enable method chaining
       }
       public function other(){
             echo "other";
             return $this; // enable method chaining
       }
}

The reason this works is the same the following works:

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

Here each method is called on an $instance but if each method returns the actual $instance back which is the same as $this, then one can combine the statements like this ("chain" them):

$instance->method1()/* returns $instance and can be used again*/->method2();

That's all there is to it.

Nikos M.
  • 8,033
  • 4
  • 36
  • 43