如何解决是否有可能在抽象构造函数中允许不同的数据类型?
长话短说:是否有可能在抽象构造函数中允许不同的数据类型?
详细问题: 我想定义一个允许多种数据类型的抽象构造函数:
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
*/
解决方法
定义抽象构造函数没有什么特别的意义。
类的构造函数在类扩展时已经不受通常的方法签名兼容性规则的约束。
所以你可以:
- 将构造函数定义为常规(非抽象)方法
- 或完全省略其定义
在这两种情况下,扩展类都可以定义他们想要/需要的任何构造函数。
但是通过将方法定义为抽象,您是在说“扩展时需要实现具有兼容签名的方法”,从而使“构造函数异常” " 无效。
,只需省略抽象类中的构造函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。