php-7.1 - 如何通过依赖注入使用 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;
}
}
推荐阅读
- c - 这个例外是什么意思?格式 %d 需要类型为“int”的参数,但参数 2 的类型为“long long unsigned int”[-Wformat]
- r - Highcharter 工具提示不适用于许多系列
- javascript - backgroundColor 以空字符串的形式出现,当我设置它的值时不会在屏幕上改变
- javascript - 如何使用 javascript 更改导航上的活动导航栏图标
- linux - 如何抑制 grep 的错误输出,使其仅返回退出状态?
- database - MongoDB:如何处理两个用户同时上传相同的用户名或密码
- github - 我如何从 Github 安装文件
- python - Python:我在为 Instagram 创建机器人时遇到错误,我该如何解决?
- ios - 使用 Swift 在 Firebase 中进行 GeoHash 查询
- excel - Excel VBA AutoFilter 选择过滤器等于 key1 和 key2 最小值的行