Skip to content

Improve type inference using information from the Class constructor #9075

@LuigiCardamone

Description

@LuigiCardamone

Feature request

Take into account this snippet:

<?php declare(strict_types = 1);

class HelloWorld
{
	private int $foo;
	
	public function __construct(): void
	{
		$this->foo = 1;
	}

	public function getFoo(): int
	{
		if (!isset($this->foo)) {
			$this->foo = 1;
		}
		
		return $this->foo;
	}
}

As you can check here https://phpstan.org/r/07727d03-eb9a-4b89-b91d-529d37cbb70a
no warning is raised at line if (!isset($this->foo)) { but we know for sure that $this->foo is initialized and different from null since it is done in the constructor. I expect PHPStan saying that condition if (!isset($this->foo)) { is always false.

I think that this check is not done since PHPStan takes into account cases in which constructor is not called (using reflection).
In my opinion, constructor skipped using reflection is a very specific use case (I think Entities with a ORM) but the majority of classes always pass from a constructor and it will be helpful to exploit that information.

What about defining a new annotation for tagging those classes that may not pass from a constructor or otherwise tagging that classes that are always instantiated with a constructor?


Did PHPStan help you today? Did it make you happy in any way?
Yes!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions