I would like to type hint class name in method parameter, in this code:
public function addScore($scoreClassName): self
{
$this->score = new $scoreClassName($this->score);
return $this;
}
$scoreClassName should be class name of a class which implements certain Interface. Something like:
public function addScore(CalculatesScore::class $scoreClassName): self
{
$this->score = new $scoreClassName($this->score);
return $this;
}
Is there any way to do it? If not, could you suggest a workaround?
EDIT: Best solution i found so far to my question
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;
}
string $scoreClassName = CalculateScore::class
would work. You'd then have to test in the method itself that the class is appropriate. – Civilitystring $scoreClassName
should work but you can't put restrictions on this. PHP does not have generics which allow for constraints like e.g. C# does – Acnode