PHP Method chaining Confusion

前端 未结 4 1812
情话喂你
情话喂你 2021-01-27 09:04

i have been lately introduced to method chaining, and am not sure if what I\'m doing here is illegal, or I\'m doing it wrong. I have a database Class like:

    c         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 09:25

    Method chaining works by returning an object from a function.

    $obj = someFunction();
    $obj->someMethod();
    

    someFunction returns an object which has a method someMethod, which you can call. Very simple stuff. You can write it like this, without explicitly storing the returned object in a variable:

    someFunction()->someMethod();
    

    The ->someMethod() simply works on whatever value someFunction returns.

    So to use method chaining, you need to return an object from your methods. An object can also return itself with return $this, so you can chain methods of the same object on itself.

提交回复
热议问题