Undefined variables in included files in php

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!

3 comments
Comment actions Permalink

Hello Adrian,

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.

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:

disable_inspection_in_file_scope.png
Thank you for feedback!

0
Comment actions Permalink

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.

0
Comment actions Permalink

Adrian,

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.

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.

0

Please sign in to leave a comment.