phpstan: Constant not found

Bug report

# phpstan-test/constant.php
<?php
namespace MyApp;
const SOMETHING = "test";
# phpstan-test/otherFile.php
<?php
namespace MyApp;
echo SOMETHING;
$ php phpstan-test/otherFile.php 
test
$ ./bin/phpstan
 433/433 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ --------------------------------------------------------------------- 
  Line   phpstan-test/otherFile.php                                           
 ------ --------------------------------------------------------------------- 
  4      Constant SOMETHING not found.                                        
         💡 Learn more at https://phpstan.org/user-guide/discovering-symbols   
 ------ ---------------------------------------------------------------------

PHP: 7.4.27 PHPStan: 1.4.2 Previous issue: #768

I can solve this issue by adding the following to my config, but I don’t think this should be necessary as both PHP and PHPStorm can find the referenced SOMETHING constant just fine:

  bootstrapFiles:
    - phpstan-test/constant.php

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

Yes, I am new to it, but love it!

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 18 (5 by maintainers)

Most upvoted comments

As you’ve already noticed in the documentation (https://phpstan.org/user-guide/discovering-symbols#global-constants), global constants need to be defined in a bootstrap file.

This is because PHPStan currently uses hybrid approach to reflection (https://phpstan.org/blog/zero-config-analysis-with-static-reflection#hybrids-are-better-for-the-environment) for performance reasons. We need the constants to be defined at runtime.

This might improve in the future when we switch to fully static reflection, I’m gonna keep this open as a feature request.

@XedinUnknown Define the constant in a boostrap file registered in PHPStan. See: https://phpstan.org/user-guide/discovering-symbols#global-constants (click on “Show obsolete instructions for older PHPStan versions” even if you have an up-to-date version).