New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
False positive for RedundantPropertyInitializationCheck
#7592
Comments
I found these snippets: https://psalm.dev/r/220b68f789<?php declare(strict_types = 1);
class A
{
/** @psalm-suppress MissingConstructor */
protected object $o;
public function getter(): object
{
if (!isset($this->o)) {
$this->o = new stdClass;
}
return $this->o;
}
}
|
Psalm and PHPStan made different choices on that matter. Based on your example, this is a horrible bug for which PHPStan is completely fine: https://phpstan.org/r/e6f0360d-2f60-4099-90f3-66d5f34489c5 What Psalm does is forcing you to initialize every property in the constructor. That's why you get a As a tradeoff, Psalm can know assume every property you have is initialized and will in turn tell you that it's pointless to check if they are. So if you have a project that relies on having uninitialized properties, you should not only suppress |
Opened #7593 to improve documentation for these issues |
Yes, for this one would expect an error but my code has an
I am fine with the |
BTW when you have code like |
This is probably a bug. Can you open an issue with a reproducer? |
I found these snippets: https://psalm.dev/r/864c8178c5<?php declare(strict_types = 1);
class A
{
/** @psalm-suppress MissingConstructor */
protected object $o;
protected bool $x = false;
public function getter(): object
{
if (!isset($this->o) || $this->x) {
$this->o = new stdClass;
}
return $this->o;
}
}
|
I think the easiest solution here is to just default-initialize to null... Then there's no risk of child classes accidentally accessing it before it's initialized, and the child classes will warn when using it that it's nullable so you get a nice hint that you should be using |
I found these snippets: https://psalm.dev/r/eb8ff4f282<?php declare(strict_types = 1);
class A
{
protected ?object $o = null;
public function getter(): object
{
if (!isset($this->o)) {
$this->o = new stdClass;
}
return $this->o;
}
}
|
I don't think the
RedundantPropertyInitializationCheck
error should be shown for this code:https://psalm.dev/r/220b68f789
phpstan correctly doesn't show any error for it https://phpstan.org/r/016e0982-ef49-492b-944d-60faed480d4f
The text was updated successfully, but these errors were encountered: