mul14
3/29/2015 - 6:51 AM

PHP Chaining method example

PHP Chaining method example

<?php

class Calc {

    protected $value;

    public static function create()
    {
        return new self;
    }

    public function add($value)
    {
        $this->value = $this->value + $value;

        return $this;
    }

    public function substract($value)
    {
        $this->value = $this->value - $value;

        return $this;
    }

    public function multiply($value)
    {
        $this->value = $this->value * $value;

        return $this;
    }

    public function divide($value)
    {
        $this->value = $this->value / $value;

        return $this;
    }

    public function get()
    {
        return $this->value;
    }
}

$result = Calc::create()->add(5)->substract(1)->multiply(4)->divide(2)->get();

var_dump($result); // 8