1

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?

2 Answers 2

2

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
 */
Sign up to request clarification or add additional context in comments.

3 Comments

It's awesome and works perfectly but is there any way to implement the hint in config.php so I won't need to type it in all the files? (specially because other objects have this problem, just like $db).
@var level comments I believe only apply to the page scope. Another workaround would be to wrap config.php code in a class, and specify $db as a property of that class, using a similar typehint in the PHPDoc comment for that property. It'll use that type hint on other pages. lmk if that's confusing and I'll edit my question with an example.
@asDca21 Try with @global instead of @var and do that in that config.php file -- in theory should work.
0

Are you sure that you include config.php after you declare $include = ['DATABASE']; ? Seems like you don't.

1 Comment

Yes. I edited the question and added the line I had forgotten.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.