【问题标题】:How to use getter & setter using dependency injection?如何通过依赖注入使用 getter 和 setter?
【发布时间】:2020-08-19 10:08:04
【问题描述】:

我正在尝试在 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.1 symfony-4.4


    【解决方案1】:

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

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多