Search code examples
phpphpstormphpdoc

Type annotations of undeclared variables


I've inherited a project that uses a home-made templating system, which works like this:

# main code

include_template('page.php', array('user' => $user, 'account' => $account));

# template 'engine'

function include_template($path, $vars) {
    extract($vars);
    include $path;
}

and the template "page.php" is an ordinary php/html file, e.g.:

 <h1><?= $user->name ?></h1>
 <p>Balance: <?= $account->balance ?></p> etc

The variables that are passed to include_template are visible in page.php because of extract, but the IDE (phpstorm) has no clue about them, so it highlights them as undefined and doesn't provide autocompletion etc. Is there a way to annotate an undeclared variable in page.php (a "bare" php/html file), so that the IDE can see it?


Solution

  • You have to declare it inside page.php. See the following code. It works in PHPStorm.

    <?php
    /**
     * @var User $user
     * @var Account $account
     */
    ?>
    <h1><?= $user->name ?></h1>
    <p>Balance: <?= $account->balance ?></p> etc