【发布时间】: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