June 22, 2011

PHP method chaining

Question by Headspin

So i was wondering if there is a way to method chain, when the initial method is a static function. Here is what I mean:

    class foo
    {
        public static function a()
        {
            $foo = new foo;
            return $foo->bar(); 
        }

        public function bar()
        {
            return $this;
        }

        public function b()
        {
            return 1;
        }
    }

    print foo::a()->b();

EDIT
print foo::a()->b(); not print foo:a()->b();

Answer by Starx

Static Methods or Other Methods, as long as the method is returning an object either self or some other, the methods can be chained, with the same method you are attempting.

class foo {
   public function __construct() {
   }
   public function create() {
       // create something;
       return $this;
   }
   public function performSomethingElse() {
      // perform something
      return $this;
   }
}
$object = new foo;

$object -> create() -> performSomethingElse();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!