我正在尝试获取类型提示以与 Symfony 5.4 安全包和 PHP 7.4 中的自定义
User
类一起使用。所以我有这个User
课程:
// src/Security/User.php
<?php
namespace App\Security;
class User implements JWTUserInterface
{
private int $customProp
public function getCustomProp() {
return $this->customProp;
}
...
}
但是每当我尝试访问某些服务中的用户时,我都没有得到
customProp
的类型提示
// src/Service/MyService.php
<?php
namespace App\Service;
use Symfony\Component\Security\Core\Security;
class MyService
{
private int $customProp;
public function __construct(Security $security) {
$this->myCustomProp = $security->getUser()->getCustomProp();
} ~~~~~~~~~~~~~
}
我收到的消息是
未定义方法“getCustomProp”。
但是值就在那里并且代码可以工作,我根本无法让 IDE 理解我的自定义
User
类提供了此方法。
您遇到这个问题是因为
Security::getUser()
是一个原生 Symfony 函数,它返回原生 Symfony UserInterface
,并且 UserInterface
没有定义 getCustomProp()
。 IDE 不知道返回的对象是自定义 User 类的实例。你可以像这样明确地告诉它:
public function __construct(Security $security) {
/** @var \App\Security\User $user */
$user = $security->getUser();
$this->myCustomProp = $user->getCustomProp();
}