Last active
September 7, 2016 13:08
-
-
Save brzuchal/e7b721e22a19cca42ec0d1f597a23baf to your computer and use it in GitHub Desktop.
Immutable classes - mutator function
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 | |
final immutable class Currency {} | |
final immutable class Money { | |
public $amount; | |
public $currency; | |
public function __construct(float $amount, Currency $currency) { | |
$this->amount = $amount; | |
$this->currency = $currency; | |
} | |
public transformer function withCurrency(Currency $currency) { | |
$this->currency = $currency; // $this is newly created clone | |
return $this; | |
} | |
public transformer function withAmount(float $amount) { | |
$this->amount = $amount; // $this is newly created clone | |
return $this; | |
} | |
} | |
$eur = new Cuurency('EUR'); | |
$usd = new Currency('USD'); | |
$totalAmount = new Money(100, $eur); | |
$usdTotalAmount = $totalAmount->withCurrency($usd)->withAmount(150); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment