Created
May 26, 2018 12:00
-
-
Save carousel/e8af06d7b9bd8b50c632b1c52143e486 to your computer and use it in GitHub Desktop.
Money pattern implemented in PHP
This file contains hidden or 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 Money | |
{ | |
private function __construct($currency, $amount) | |
{ | |
$this->currency = $currency; | |
$this->amount = $amount; | |
} | |
public static function fromString($currency, $amount) | |
{ | |
return new self($currency, $amount); | |
} | |
public function __toString() | |
{ | |
return $this->amount . "" . $this->currency; | |
} | |
private function getAmount() | |
{ | |
return $this->amount; | |
} | |
private function getCurrency() | |
{ | |
return $this->currency; | |
} | |
public function add(Money $money) | |
{ | |
if ($money->getCurrency() != $this->getCurrency()) { | |
throw new Exception('Money should have equal currencies'); | |
} | |
return new Money($money->getAmount() + $this->getAmount(), $money->getCurrency()); | |
} | |
public static function __callStatic($method, $args) | |
{ | |
return (new Money($method, $args[0])); | |
} | |
} | |
$money = Money::fromString('EUR', 200); | |
$money1 = Money::fromString('$', 882); | |
$newAmount = $money1->add($money1); | |
echo 'Now we have: ' . $newAmount . "\n"; | |
echo 'Calling static: ' . Money::EUR(150000)->add($money); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment