Search code examples
phpphpstorm

PhpStorm undefined object if class is included in conditional statement


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:

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

index.php

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

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.

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?


Solution

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

    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
     */