php - 在 php 中键入提示 ClassName

标签 php oop

我想在方法参数中键入提示类名,在这段代码中:

    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/

相关文章:

javascript constructor.prototype继承另一个constructor.prototype

php - 将来自 2 个不同来源的数据插入到 MySQL 的一张表中

java - 如何直接访问最小堆中的对象,java

c++ - 使用函数继承类,具有静态成员

php - 语法错误或访问冲突 : 1103 Incorrect table name with $_POST array data

java - 如何连接 UI 和业务逻辑

oop - 面向对象编程不仅仅是方法?

php - 从 td 调用 jQuery

php - 如何将动态创建的输入框的值插入数据库

php - 如何在 PHP 中调用函数