我正在尝试为Euro,Doller等不同货币实施货币形成器类.
我试图创建一个抽象类,并希望从这个类扩展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,因为分隔符,小数点等在格式化程序生命周期中不会改变.如果你想让你的班级做的就是格式化货币,我认为你也不需要所有的吸气剂.
如果你的班级只负责格式化,我认为你不应该把价值作为一个类字段;也许最好将它作为参数传递给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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。