【问题标题】:Is there a possibility to allow different data types in an abstract constructor?是否有可能在抽象构造函数中允许不同的数据类型?
【发布时间】:2021-09-05 02:20:49
【问题描述】:

长话短说:是否有可能在抽象构造函数中允许不同的数据类型?

详细问题: 我想定义一个允许多种数据类型的抽象构造函数:

abstract class ValidationRule
{
  protected $ruleValue;
  protected $errorMessage;

  abstract public function __construct($ruleValue); // see here

  protected function setErrorMessage($text)
  {
    $this->errorMessage = $text;
  }
}

扩展类现在实现了抽象构造函数。 我希望构造函数允许不同的数据类型(int、bool、string、...)。


class MinCharacters extends ValidationRule
{
  public function __construct(int $ruleValue) // see here
  {
    $this->ruleValue = $ruleValue;
    $this->setErrorMessage("At least " . $this->ruleValue . " characters necessary.");
  }
}

class Required extends ValidationRule
{
  public function __construct(bool $ruleValue) // and here
  {
    $this->ruleValue = $ruleValue;
    $this->setErrorMessage("Field required.");
  }
}

当我实例化一个对象时,我收到以下错误。我知道这个问题,但想知道是否有任何解决方案如何在构造函数中允许多种数据类型。


$rule = new MinCharacters(5);
/*
Fatal error: Declaration of MinCharacters::__construct(int $ruleValue) 
must be compatible with ValidationRule::__construct($ruleValue) in 
/opt/lampp/htdocs/index.php on line 51
*/

【问题讨论】:

  • AFAIK 只要您使用类型提示,就不可能。但是我没有看到将构造函数定义为抽象的任何好处,但是类

标签: php oop abstract-class


【解决方案1】:

定义抽象构造函数没有什么特别的意义。

类的构造函数在类扩展时已经免除了通常的方法签名兼容性规则。

所以你可以:

  • 将构造函数定义为常规(非抽象)方法
  • 或完全省略其定义

在这两种情况下,扩展类都可以定义他们想要/需要的任何构造函数。

但是通过将方法定义为abstract,您是在说“扩展时需要实现兼容签名的方法”,从而使“构造函数异常” " 无效。

【讨论】:

    【解决方案2】:

    只需省略抽象类中的构造函数即可。

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 2017-06-04
      • 2010-09-20
      相关资源
      最近更新 更多