Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable in PHPStan but it's declared elsewhere

How do you deal with these scenarios in PHPStan:

  1. Say you're using plain PHP as template engine. E.g.,
// view.php

<b><?=$foo?></b>

  1. Say you have 2 files a.php and b.php
// a.php     
$foo = 'bar';

// b.php     
require 'a.php';     
echo $foo;

PHPStan will both report this as Undefined variable: $foo

How do you deal with this? Can PHPStan be configured to somehow execute your app so it knows that these variables are actually defined during runtime?

like image 410
IMB Avatar asked Aug 06 '26 10:08

IMB


2 Answers

You can try to use the phpstan.neon solution provided in phpstan#104 (comment):

You can ignore error for specific variables by using regular expressions, even in specific directories. In your case you can use:

parameters:
    ignoreErrors:
        -
            message: '#Undefined variable: \$foo.*#'
            path: my/directory/*
/** @var string $foo */

echo $foo; // No error

echo $unintededUndeclaredVariable; // Error
like image 58
nelson6e65 Avatar answered Aug 08 '26 01:08

nelson6e65


All you need to do is perform a check to ensure the variable is set.

e.g.

if (isset($foo)) {
    echo $foo;
}

or something like the following if you're not wanting to wrap all your code in an if.

if (! isset($foo)) {
    throw new Exception('$foo not set');
}
like image 22
George Avatar answered Aug 08 '26 00:08

George



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!