Chain Method with PHP

When many of you have studied the written classes, you may have encountered a writing style like this.

$text = new Text();
echo $text->write('PHPEXAMPLE')->color('red')->fontSize('20px')->show();

Let's create our class for this example now.

class Text {

    private $text;
    private $style;

    public function write($text)
    {
        $this->text = $text;
    }

    public function color($color)
    {
        $this->style .= 'color: ' . $color . ';';
    }

    public function fontSize($size)
    {
        $this->style .= 'font-size: ' . $size . ';';
    }

    public function show()
    {
        return '<div style="' . $this->style . '">' . $this->text . '</div>';
    }
}

However, this example will throw an error. Because what you need to do for such a writing style is to return your $this object. So if we organize our class like this;

class Text {
    
    private $text;
    private $style;

    public function write($text)
    {
        $this->text = $text;
        return $this;
    }

    public function color($color)
    {
        $this->style .= 'color: ' . $color . ';';
        return $this;
    }

    public function fontSize($size)
    {
        $this->style .= 'font-size: ' . $size . ';';
        return $this;
    }

    public function show()
    {
        return '<div style="' . $this->style . '">' . $this->text . '</div>';
    }

}

Now we are ready to use it in this way.

The chain method also works in the same logic in jQuery. This is probably the case for every language. For example, if I need to give an example in jQuery, let's prepare a simple plugin.

$.fn.Text = function(text){
    $(this).html(text);
};

$('body').Text('PHPEXAMPLE').css({
    'color': 'red',
    'font-size': '20px'
});
Comments

There are no comments, make the firs comment