Page 1 of 1

Nested Method calling in php

Posted: Sun Aug 14, 2011 7:14 am
by tanvirtonu
I m new to php programming. I want to know what is the meaning of double " -> " in php method calling. Like the one in the following example -

$this->load->library('class_name', $config, 'object name')

Does it mean that the "load" method has the "library" method in it...I m confused..

Re: Nested Method calling in php

Posted: Sun Aug 14, 2011 7:46 am
by AbraCadaver
It is called method chaining. So long as the method returns an object you can do this. load() is called and it returns an object, most likely $this and then the library() method is called. Pretty much the same as this:

Code: Select all

$this->load();
$this->library('class_name', $config, 'object name');

Re: Nested Method calling in php

Posted: Sun Aug 14, 2011 8:19 am
by tanvirtonu
THANKS A LOT BRO...

But I think load doesnt return $this object, I guess, $this calla load, then load return some object which in turn call library method, correct me if I am wrong
Can I do this then (if possible) - $obj1->$obj2->$obj3->$obj4->$obj5->.............

Re: Nested Method calling in php

Posted: Sun Aug 14, 2011 8:28 am
by AbraCadaver
Well no. The -> is accessing a property or method. It works like this:

Code: Select all

class Test {
   
   function load() {
      // do some stuff
      return $this;
   }

   function execute() {
      // do more stuff
      return $this;
   }

   function display() {
      // display something
   }
}

$obj = new Test();
$obj->load()->execute()->display();

Re: Nested Method calling in php

Posted: Sun Aug 14, 2011 8:38 am
by AbraCadaver
tanvirtonu wrote:THANKS A LOT BRO...

But I think load doesnt return $this object, I guess, $this calla load, then load return some object which in turn call library method, correct me if I am wrong
Can I do this then (if possible) - $obj1->$obj2->$obj3->$obj4->$obj5->.............
For the original code to work, load would be an object property of $this that is an object itself that contained a method called library().

Re: Nested Method calling in php

Posted: Mon Aug 15, 2011 12:27 am
by tanvirtonu
AbraCadaver wrote:Well no. The -> is accessing a property or method. It works like this:

Code: Select all

class Test {
   
   function load() {
      // do some stuff
      return $this;
   }

   function execute() {
      // do more stuff
      return $this;
   }

   function display() {
      // display something
   }
}

$obj = new Test();
$obj->load()->execute()->display();
NOW, THIS IS VERY CLEAR.....THANKS BRO..
But cant it be different object in each method call , e.g. - $obj1 -> method1 - > method2 , here method1 returns $obj2 which has the method2 , cant it work this way