Search code examples
phpphpstorm

How to set PHPStorm to check for variable usage in required/included files? How to check variable definition in required/included files?


When I require or include a file in PHPStorm, it's not being able to detect that a variable defined in the main file is being used in that file that is being required/included. Same thing with the variable in the included/required file, it shows as not defined.

Here's an example for clarity:

Main file (let's say main.php):

<?php
$var1 = "hi";
require "next.php";

While here is the "required" next.php file:

<?php
echo "<p>".$var1."</p>";

The code works fine but on PHPStorm, $var1 shows as unused in the main.php file while it shows as undefined in the next.php file.

I've seen several answers on SO on how to disable the warnings but that's not what I want. I want PHPStorm to recognize this variable as used and defined in the called and calling modules respectively.

Is this possible? Or am I asking the wrong questions?

If anyone's wondering why I'm doing this, I'm trying to separate logic from structure ala-MVC.


Solution

  • The issue is that just looking at next.php by itself, the variable is unequivocally undefined. There's no guarantee how next.php will be executed. You cannot restrict the file to only be executed when included from another file. You can execute this file by itself, in which case it will fail. Or you can include it from infinitely many other files which do not set this variable, in which case it will fail.

    That is why PhpStorm is nagging you about this undefined variable. It is bad coding style because it can fail in any number of circumstances.