Search code examples
phpphpstan

Can phpstan detect "Typed property ... must not be accessed before initialization" Errors?


I have a PHP program,

<?php
class Zap {
}

class Zip {
    public Zap $zap;
}
$object = new Zip;

var_dump(
    $object->zap
);

This program produces an error because of an initialized non-nullable property.

Fatal error: Uncaught Error: Typed property Zip::$zap must not be accessed before initialization in

Can phpstan detect these sorts of errors? I've scanned this program at the highest level, and phpstan seems happy

% ./vendor/bin/phpstan analyse --level=8 /tmp/test.php
 1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%


                                                                                                                        
 [OK] No errors                                                                                                         

If phpstan can't detect these situations, is there another PHP Static Analyzer that can?


Solution

  • It looks like the ability to scan for uninitialized property values was added in July of 2020

    However, this feature is disabled by default. You'll need to be using a configuration file that sets the checkUninitializedProperties value

    % cat phpstan.neon 
    parameters:
        checkUninitializedProperties: true
    
    and then tell `phpstan` to use this configuration file.
    
     % ./vendor/bin/phpstan analyse --level=8 --configuration=./phpstan.neon /tmp/test.php
     1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
    
     ------ ------------------------------------------------------------------------------------------------------ 
      Line   /tmp/test.php                                                                                         
     ------ ------------------------------------------------------------------------------------------------------ 
      6      Class Zip has an uninitialized property $zap. Give it default value or assign it in the constructor.  
     ------ ------------------------------------------------------------------------------------------------------ 
    
                                                                                                                    
     [ERROR] Found 1 error                                                                                                  
    

    Also, at the risk of saying the obvious part loud, this check assumes a particular style of programming. For example, the following valid PHP program

    <?php
    class Zap {
    }
    
    class Zip {
        public Zap $zap;
    }
    $object = new Zip;
    $object->zap = new Zap;
    var_dump(
        $object->zap
    );
    

    Still fails the checkUninitializedProperties check.