如何通过依赖注入使用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参数。

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

任何人都可以帮助我。

谢谢。

解决方法

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

}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...