Created
March 29, 2015 06:51
-
-
Save mul14/680eceb12b3701c850a7 to your computer and use it in GitHub Desktop.
PHP Chaining method example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
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
mas saat saya mau initiate property
$value
pada saat pemanggilan methodcreate()
bagaimana caranya?Saya menggunakan
di dalam method
create()
tidak bisa.