PHPStan: “Class not found” error when autoloaded class extends discovered parent class
If you’re getting a “Class * not found” error with PHPStan, check to see whether you’re having a class auto-loaded by composer extend a parent class that is discovered via scanDirectories
. For example,
<?php namespace MyApp\Form\Field; class CountryField extend \BaseField { }
If CountryField
is auto-loaded by composer (when the classmap was built with composer dumpautoload), but the \BaseField
class is discovered using scanDirectories
then PHPStan will complain that it is not able to find \BaseField
because PHPStan expects the parent class to also be auto-loadable. A way to fix this is to create an autoloader for the third party library, but in most cases that is not possible, hence the use of scanDirectories. In that case, PHPStan has an undocumented experimental flag called disableRuntimeReflectionProvider
that will disable runtime reflection, and enable full static analysis. Use like this:
parameters: featureToggles: disableRuntimeReflectionProvider: true level: max scanDirectories: - /var/www/your-third-party-library
This will degrade PHPStan analysis performance, however from my observations, this will only happen for situations where this issue arises (an autoloaded class extending a class that is discovered using Discovering Symbols). In other files that are not affected by this issue, the performance is unaffected. I am using PHPStorm with the PHPStan plugin, so the analysis is done per file when it is changed, so this performance degradation is acceptable for the limited number of files that are affected by this issue.
You can read more about this from these two Github issues:
- https://github.com/phpstan/phpstan/issues/4796#issuecomment-812913262
- https://github.com/phpstan/phpstan/discussions/6339#discussioncomment-1941304