Skip to content

Instantly share code, notes, and snippets.

@brzuchal
Last active September 7, 2016 13:08
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 brzuchal/e7b721e22a19cca42ec0d1f597a23baf to your computer and use it in GitHub Desktop.
Save brzuchal/e7b721e22a19cca42ec0d1f597a23baf to your computer and use it in GitHub Desktop.
Immutable classes - mutator function
<?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