How can I document a constant that is defined in external code using PhpDoc/DocBlocks so that it will not show up as an undefined variable in static code analysis?
I'm trying to write a small WordPress plugin. I have some PHP code like below.
defined('ABSPATH') or die('Access denied!'); // Avoid direct file request
function getPluginInfo($key) {
require_once ABSPATH . '/wp-admin/includes/plugin.php';
$data = get_plugin_data(MY_PLUGIN_FILE, true, false);
return $data[$key];
}
I'm using the VSCode plugin vscode-intelephense (which provides a PHP language service). I have all the necessary dependencies installed, including listing "wordpress" as a stub in the VSCode settings. In general, the intelephense is working quite well and is doing a great job of showing information about my code as well as WordPress library code.
However intelephense shows an error: "Undefined constant '...\ABSPATH' (1011)" (where the dots are a namespace that I have omitted for brevity).
So it appears that intelephense doesn't pick up on the condition implied by the first line -- namely that if ABSPATH
isn't defined, execution won't reach the later code that references it. (Which is perfectly fine, program flow analysis might be demanding too much). Anyway, I think I should be able to add some kind of PhpDoc (or another commented annotation) to indicate to code analyzers that the variable is defined. Something like this:
/**
* @var string ABSPATH
*/
or this:
/**
* @global string ABSPATH
*/
But neither of those cause the error to go away. (I also tried @const
which doesn't appear to be a real tag. It didn't work either.)
Is there some way in the code I can indicate that ABSPATH is defined in external code or in an out scope? Adding a line at the top of the function like global ABSPATH;
doesn't seem to be right either, because ABSPATH
isn't a variable. It's a define
-created constant.
Thanks!
Similar to the wordpress stub that you have enabled to give you wp intellisense, you would have to create a stub file for your constants and add it to your workspace so that it can be indexed.
<?php
const ABSPATH = '';