是否有可能在抽象构造函数中允许不同的数据类型



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

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

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
*/

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

扩展类时,类的构造函数已经不受通常的方法签名兼容性规则的约束。

所以你可以:

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

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

但是,通过将该方法定义为抽象,您就是在说">当扩展"时需要实现兼容签名的方法;,从而使";构造函数异常";无效的

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

最新更新