简体   繁体   中英

Type hinting ClassName in php

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;
    }

You can't type-hint on a specific string. You can, however, set a default string value.

To ensure you've instantiated a class of the correct type you'd have to do a check in the method body itself.

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;
}

I'd argue that this isn't really the right way to do it, you should probably be using dependency injection instead, and instantiate the score class prior to passing it to this class. It makes the dependency more explicit and simpler to control. The actual code is also a lot simpler.

public function addScore(CalculatesScore $scoreClass): self
{
    $this->score = $scoreClass;
    return $this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM