关于这个例子的问题:
<?php declare(strict_types=1);
class SomeTestClass
{
/** @var string|null */
private $name;
/** @var string */
private $sth;
public function getName(): ?string
{
return $this->name;
}
public function setSomething(string $value): void
{
$this->sth = $value;
}
public function something(): void
{
$this->setSomething($this->getName());
}
}
为什么 PhpStorm 2018.3.5 没有通知我 something()
中与使用可为 null 的值作为不应为 null 的方法参数相关的错误代码?我问这个是因为当 $name
属性为 null
时,我的应用程序就会出错。
版本与
public function something(): void
{
/** @var string|null $name */
$name = $this->getName();
$this->setSomething($name);
}
也不行。
最佳答案
PhpStorm 在分析代码时不是很严格。例如,当通过构造函数注入(inject)属性值时,它不会在自动完成方法和属性时查看声明的属性类型,而是查看注入(inject)到构造函数中的类型。
要进行非常严格的分析,请尝试 PHPStan .与 PhpStorm 不同,您可以轻松地将其添加到您的 CI 构建中。 See the resulting error for your example .
关于PhpStorm - 关于 NULL 值的检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55339507/