1

我有一个 PHP 程序,

<?php
class Zap {
}

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

var_dump(
    $object->zap
);

由于初始化的不可为空的属性,此程序会产生错误。

致命错误:未捕获错误:在初始化之前不得访问类型化属性 Zip::$zap

phpstan检测出这些错误吗?我已经在最高级别扫描了这个程序,并且phpstan似乎很高兴

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


                                                                                                                        
 [OK] No errors                                                                                                         

如果phpstan无法检测到这些情况,是否有另一个 PHP 静态分析器可以?

4

1 回答 1

2

似乎在 2020 年 7 月添加了扫描未初始化属性值的功能

但是,默认情况下禁用此功能。您需要使用设置checkUninitializedProperties值的配置文件

% 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.

于 2021-06-21T18:58:20.543 回答