Search code examples
phpooplaravelfluent-interfacemethod-chaining

What do this called in PHP


In a code like the following may be found:

return View::make('hello')->with('name', $name);

What I know is that:

  • View is a class
  • make is one method of the class View
  • 'hello' is a parameter passed to the method make

What I don't know is: with does it a method of method?! does it a PHP keyword? or does it something defined (if it is, what is its definition?) in the make method?


Solution

  • class View() {
      protected $name;
      public function __construct($name){$this->name = $name;}
      public function with($s, $p){return $this;}
      public static function make($name){
        return new self($name);
      }
    }
    

    make - static method of a class
    with - method of View object

    Look at View::make('hello')->with('name', $name); as at followed:

    $view = View::make('hello');
    $view->with('name', $name);
    

    return $thisin with method allows us to followed:

    View::make('hello')->with('name1', $name1)
                       ->with('name2', $name2)
                       ->with('name3', $name3);
    

    This pattern named chaining