PhpStorm未定义对象(如果条件语句中包含类) [英] PhpStorm undefined object if class is included in conditional statement

查看:265
本文介绍了PhpStorm未定义对象(如果条件语句中包含类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果条件语句中包含变量,JetBrains PhpStorm不会将变量检测为类的对象.例如,这是我的文件:

JetBrains PhpStorm doesn't detect a variable as an object of a class if it's included in a conditional statement. For example, here are my files:

config.php:

config.php:

if( in_array('DATABASE', $include) ){
        require_once( 'database/Database.class.php' );
        $db = new Database();
}

index.php

index.php

$include = ['DATABASE'];
require_once('config.php');
$db...  //<< Here $db is undefined

如果我在不检查条件的情况下将数据库类包含在config.php文件中,就可以了,并且我可以将$db用作数据库类的实例.

if I include database class in config.php file without checking the condition, it'll be OK and I can use $db as an instance of Database class.

我还尝试在检查器中取消选中Ignore 'include' and 'require' statements.,但是它只是忽略未定义的变量,$db不会被检测为对象,因此我看不到它的方法和属性.

I also tried to uncheck Ignore 'include' and 'require' statements. in the inspector but it just ignores undefined variables, $db is not detected as object by the way so I can't see it's methods and properties.

我应该如何解决此问题?

How should I fix this issue?

推荐答案

不确定$db到底是什么,因为它是在语句中定义的.直到运行时,才会知道DATABASE是否在$ include数组中,因此$ db可能会或根本不会定义.

It's not sure what $db is precisely because it was defined inside the if statement. It won't know until run time if DATABASE is in the $include array, so $db may or may not be defined at all.

您可以通过使用PHPDoc注释代替该类型来解决此问题.在index.php的顶部添加类似以下内容:

You can work around it by using PHPDoc comments to hint at the type instead. At the top of index.php add something like:

<?
/**
 * @var Database $dba
 */

这篇关于PhpStorm未定义对象(如果条件语句中包含类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆