Skip to content

Instantly share code, notes, and snippets.

@mul14
Created March 29, 2015 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mul14/680eceb12b3701c850a7 to your computer and use it in GitHub Desktop.
Save mul14/680eceb12b3701c850a7 to your computer and use it in GitHub Desktop.
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
@fathur
Copy link

fathur commented Mar 29, 2015

mas saat saya mau initiate property $value pada saat pemanggilan method create() bagaimana caranya?

Saya menggunakan

public static function create()
{
        $this->value = 100
        return new self;
}

di dalam method create() tidak bisa.

@mul14
Copy link
Author

mul14 commented Mar 29, 2015

Hmm, pertama bisa langsung set di property protected $value = 100. Atau seperti ini

public static function create()
{
    $instance = new self;

    $instance->value = 100;

    return $instance;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment