我正在尝试为不同的货币(如欧元、美元等)实现一个货币格式化程序类。
我试图创建一个抽象类,并希望从这个类扩展euro和doller类。
因为我是php新手,不知道这是否是实现这种想法的更好方法。
abstract class Currency {
private $name;
private $symbol;
private $decimal;
private $decimal_point;
private $thousand_sep;
function __construct() {
}
function setName($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
function setSymbol($symbol) {
$this->symbol = $symbol;
}
function getSymbol() {
return $symbol;
}
function setDecimal($decimal) {
$this->decimal = $decimal;
}
function getDecimal() {
return $this->decimal;
}
function setDecimalPoint($decimal_point) {
$this->decimal_point = $decimal_point;
}
function getDecimalPoint() {
$this->decimal_point;
}
function setThousandSeprator($thousand_sep) {
$this->thousand_sep = $thousand_sep;
}
function getThousandSeprator() {
return $this->thousand_sep;
}
function display() {
return $this->symbol . number_format($this->amount, $this->decimal, $this->decimal_point, $this->thousand_sep);
}
}
最佳答案
我认为您不需要所有这些setter,因为分隔符、小数点等在格式化程序的生命周期中不会改变。如果你只想让你的类格式化货币,我认为你也不需要所有的getter。
如果您的类只负责格式化,我认为您不应该将值保留为类字段;最好将其作为参数传递给display()
。
这样怎么样:
abstract class CurrencyFormatter {
protected $name;
protected $symbol;
protected $decimal;
protected $decimal_point;
protected $thousand_sep;
function format($amount) {
return $this->symbol . number_format($amount, $this->decimal, $this->decimal_point, $this->thousand_sep);
}
}
class EuroFormatter extends CurrencyFormatter {
public function __construct() {
$this->name = "Euro";
$this->symbol = "E";
$this->decimal = 2;
$this->decimal_point = ".";
$this->thousand_sep = ",";
}
}
然后,你可以这样使用它:
$formattedAmount = new EuroFormatter()->format(123);