phpstan: Adding `@var` Should not be needed when the property is set by the constructor
Hello
Summary of a problem or a feature request
With this code:
class Foobar
{
private $httpClient;
public function __construct(HttpClient $httpClient)
{
$this->httpClient = $httpClient;
}
public function fetchOrientationToken()
{
$this->httpClient->methodDoesNotExist();
}
}
There are no errors
With this code:
class Foobar
{
/** @var HttpClient */ // <----------- the difference is here
private $httpClient;
public function __construct(HttpClient $httpClient)
{
$this->httpClient = $httpClient;
}
public function fetchOrientationToken()
{
$this->httpClient->methodDoesNotExist();
}
}
A violation is raised
Code snippet that reproduces the problem
https://phpstan.org/r/a6aeb2711d867c2bda6e388ee515e9c4
Expected output
A violation should be raised in both situation
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 2
- Comments: 27 (26 by maintainers)
I think that you should add
@vars to your properties, it’s future-proofing for PHP 7.4 where you will be able to type your properties natively. I’m quite sure that there will be a fixable sniff in slevomat/coding-standard that will move your typehints from phpDoc to native once 7.4 is out 😃Symfony’s coding standards state to not add the PHPDoc to a property if it can be inferred from the constructor, it is also the default configuration of PHP CS Fixer and it is considered a best practice by some.
It would be nice to have this option at least for interoperablility with other tools in the ecosystem.
Good news! PHPStan 0.11.10 includes support for inferring private property type from constructor! https://github.com/phpstan/phpstan/releases/tag/0.11.10
I understand you don’t want to add this option. I will live with it but I really wanted this feature. More over as @dunglas said, we remove all theses PHP Doc in Symfony, and it’s the same for the SF community.
Do you know if we can build a plugin to do that?
No, if you’re using PHPStan it’s not just PHPDoc 😉 PHPStan will complain.
@lyrixx It does. The type of the property can change at any time, it is not fixed after the constructor. Adding a
@varpins the type and prevents you from setting it to something it shouldn’t be.@lyrixx Would you expect the following code to report error? https://phpstan.org/r/4315bb3d9a7f14278be47f2ffb775344