Undefined variables in included files in php Follow
Hello,
I am new to this forum, my name is Adrian.
I have a question:
When I use "Inspect code" in phpStorm on my php-Project, I get "Undefined variables errors" in files which are included by other files and that use variables of that files.
E.g.:
mainfile.php
$testvar="Hello world";
.
.
include ($includefile);
includefile.php
echo $testvar;
So I get an error in includefile.php, becuase $testvar is not declared there.
What is my mistake? Is there a workaround.
Additionally I have to tell you that the include-files are included dynamically becuase they must be included with relative paths on my server.
The project works fine, but I dont like to have errors there in phpstorm.
Thank you!
Please sign in to leave a comment.
Hello Adrian,
Generally information about included files only available in runtime, so 'Undefined Variable' analysis, as a kind of static code analysis, doesn't have access to such information.
The inspection works good in function/method scopes(we rarely use include/require operators inside function/methods), but can produce a lot of false positives in file scope(it depends on programming style).
You can disable the inspection in the file scope:
Thank you for feedback!
Hello Nikolay,
thank you.
Yes, I realized that this works much much better when using functions than includes, so I change my project to use very few includes.
I think, using functions is maybe the better style because you have to define the variables you need and everything will be fine.
One bad thing with functions is, that there are sometimes functions with a lot of parameters, but all in all it is the better way I think.
Thank you, sincerely, Adrian.
Adrian,
PhpStorm doesn't impose to use definite programming style, but I believe that code fragment which cannot be analyzed with static code analysis tool, will be complex for human too.