Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What 's method chaining? how to implement it on PHP?

user-image
Question added by Adel Ezat Fawzy Ellozy , Webdeveloper. , Saudi Arabian Maritiem Sports Federation
Date Posted: 2017/03/11
Ashraf CA
by Ashraf CA , DIGITAL MARKETING & MULTIMEDIA DESIGNER , Standard Marconi DMCC

Its rather simple really, you have a series of mutator methods that all returns the original (or other) objects, that way you can keep calling functions.

 

Example:

<?php

class fakeString

{

    private $str;

    function __construct()

    {

        $this->str = "";

    }

 

    function addA()

    {

        $this->str .= "a";

        return $this;

    }

 

    function addB()

    {

        $this->str .= "b";

        return $this;

    }

 

    function getStr()

    {

        return $this->str;

    }

}

 

 

$a = new fakeString();

 

 

 

echo $a->addA()->addB()->getStr();

 

 

This outputs "ab"

 

Mohamed saleh
by Mohamed saleh , PHP Laravel Developer , babeleye

The ability to return one object from multi functions.

class fakeString { private $str; function __construct() { $this->str = ""; } function addA() { $this->str .= "a"; return $this; } function addB() { $this->str .= "b"; return $this; } function getStr() { return $this->str; } } $a = new fakeString(); echo $a->addA()->addB()->getStr();

More Questions Like This