phptools-docs
phptools-docs copied to clipboard
Inconsistent behavior with unrecognized global variable outside vs inside use()
I have a php file called whatever.php in my project, whose code is this:
<?php
global $vbulletin;
if (!$vbulletin) exit;
$values = array_map(
function($_id) use($joinusergroupid) {
return "($_id, $joinusergroupid, 0)";
},
array_unique(array_filter(explode(",", $ids)))
);
if (!empty($values)) {
$vbulletin->db->query_write("
REPLACE INTO " . TABLE_PREFIX . "vbpsmt_user_x_group (userid, usergroupid, is_primary)
VALUES " . implode(", ", $values) . "
");
}
I get this error for this variable:
That is not surprising, because this file gets include()d in a very convoluted way from somewhere else (a string containing PHP code gets loaded from a database, then gets eval()ed, and that evaled code contains the include() statements that calls this file), where the variable is actually defined. So, I would never expect the IDE to be able to figure out that this variable is actually defined when the code gets executed.
However, look what happens when I add this line:
Now the IDE claims to know that $joinusergroupid is a global variable the first time I'm reading it.
And now it no longer complains about it in the use statements of the callable.
This makes no sense. Either the IDE is able to figure out that the variable has been assigned in this context, in which case it should be fine in both cases, or it is not, in which case it should be an error in both cases.
Thank you for the test case!
This is a kind of magic - global variables are treated very vaguely. But within use, we check them more strictly. Once the variable is used outside the use (), you basically "convince" the editor, that the variable probably really exists, so it won't bother you with it.
global $joinusergroupid; // this would make the editor happy
I agree, we should be more consistent here.