Hilmi Erdem KEREN
Hilmi Erdem KEREN

Reputation: 1999

Php Calling the functions of same class one after another

I want to write something like (laravel uses):

View::make('FooBarView')->with('foo', $foo)
                        ->with('bar', $bar);

My knowledge and imagination made me to use new self instances. But I don't think that this is the best idea around and I could not handle it.

Google couldn't help me because of my bad keywords I think. I don't want to make you write code for me for sure but what is the name of this design pattern or whatever?

In laravel's source, with function uses

return $this;

But how to use it after make?

By the way, in this example; with method helps you to set variables for view's render.

Upvotes: 2

Views: 546

Answers (1)

Jite
Jite

Reputation: 5847

To call what the function returns, the function will have to return something that is possible to call.

In this case, you could for example return "this":

class View {
  /** 
  * @returns View
  */
  public static function make($foo) { 
    /* do stuff, return new View instance */ 
    return new View();
  }
  /** 
  * @returns View
  */
  public function with($foo, $bar){
    /* do stuff */
    return $this;
  }
}

That way, whenever you call with you will get the class instance back, which in turn will be callable:

 View::make("foo")->with("foo")->with("bar");
 // Will be same as:
 $v = View::make("foo");
 $v = $v->with("foo");
 $v = $v->with("bar");

Upvotes: 4

Related Questions