我想在方法参数中键入提示类名,在这段代码中:
public function addScore($scoreClassName): self
{
$this->score = new $scoreClassName($this->score);
return $this;
}
$scoreClassName 应该是实现某个接口(interface)的类的类名。像这样的东西:
public function addScore(CalculatesScore::class $scoreClassName): self
{
$this->score = new $scoreClassName($this->score);
return $this;
}
有什么办法吗?如果没有,您能否建议解决方法?
编辑:到目前为止我找到的最佳解决方案
public function addScore(string $scoreClassName): self
{
$implementedInterfaces = class_implements($scoreClassName);
if (!in_array(CalculatesScore::class, $implementedInterfaces))
{
throw new \TypeError($this->getTypeErrorMessage($scoreClassName));
}
$this->score = new $scoreClassName($this->score);
return $this;
}
最佳答案
您不能对特定字符串进行类型提示。但是,您可以设置默认字符串值。
为确保实例化的类类型正确,您必须检查方法主体本身。
public function addScore(string $scoreClassName = CalculatesScore::class): self
{
$score = new $scoreClassName($this->score);
if (!$score instanceof CalculatesScore)
{
throw new InvalidArgumentException("Invalid class score type: $scoreClassName");
}
$this->score = $score;
return $this;
}
我认为这并不是真正正确的方法,您可能应该改用依赖注入(inject),并在将分数类传递给此类之前实例化它。它使依赖关系更明确,更易于控制。实际代码也简单很多。
public function addScore(CalculatesScore $scoreClass): self
{
$this->score = $scoreClass;
return $this;
}
关于php - 在 php 中键入提示 ClassName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173072/