首页 > 解决方案 > 如何通过依赖注入使用 getter 和 setter?

问题描述

我正在尝试在 Symfony 中实现依赖注入。

我创建了一个名为 Token 的类,如下所示:

class Token
{
    private $token;
    private $key;

    public function __construct(string $key)
    {
        $this->key = $key;
        $this->settoken();
    }

    public function getToken(): string
    {
        return $this->token;
    }

    public function setToken(string $newString)
    {
        $token = $newString . '-' . $this->key;

        return $this;
    }

}

在构造中,我有一个定义在services.yml

现在我已经将这个类注入到另一个控制器中,如下所示。

$this->token->setToken('123456789');

dd($this->token->getToken())

但这给了我“函数 setToken() 的参数太少”错误。我认为这是因为在我的 Token 类构造中我已经传递了 key 参数。

我不确定如何正确使用它。

谁能帮帮我吗。

谢谢你。

标签: php-7.1symfony-4.4

解决方案


我在 Token 类中看到了问题。如果您查看 __construct,您正在调用$this->settoken()

public function __construct(string $key)
{
    $this->key = $key;
    $this->settoken();
}

下面是 setToken 方法,它有一个字符串作为强制参数。这就是为什么它给你一个错误。

该类应如下所示:

class Token {

private $token;
private $key;

public function __construct(string $key)
{
    $this->key = $key;
}

public function getToken(): string
{
    return $this->token;
}

public function setToken(string $newString): Token
{
    $this->token = $newString . '-' . $this->key;

    return $this;
}

}


推荐阅读