php – 我怎样才能以更好的方式扩展这个抽象类

我正在尝试为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);

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...