How to specify variable scope

In some classes I've a code like this:

function my_method() {

     $something = array();

     if ( $a != $b ) {

           $something = $this->my_other_method( $a, $b);

     }



     include SOME_CONSTANT . '/menu/my-menu.php';
}


PhpStorm complains that $something is not used, but it is used, but my-menu.php.
How couldI tell that the variable is used there, without disabling inspection (something that I would have to do in two places and that looks ugly especially when working in a team, with people that don't use PhpStorm)?

Thanks.
2 comments

Hi there,

How couldI tell that the variable is used there, without disabling inspection

AFAIK you cannot.

I mean -- you can suppress inspection for a line (placing such comment just before those lines) .. but as I understand you want to avoid this:

/** @noinspection PhpUnusedLocalVariableInspection */
$something = $this->my_other_method( $a, $b);


The only alternative I see is to write your code differently -- do not use such "declare-here + then-include + then-use-elsewhere" approach. You could use something like this instead (rough example):

function my_method()
{
    $something = array ();

    if ($a != $b) {
        $something = $this->my_other_method($a, $b);
    }

    $data = array(
        'something' => $something,
    );
    include SOME_CONSTANT . '/menu/my-menu.php';
    print_my_menu($data); // function from the above included file that will print your menu
}
0

That's not a goot solution for me: the variable is used inside the include file, in many places.

What I don't understand is why I can't just tell PhpStorm that a variable is used in an include file.

There is a specific PhpDoc for that (@used_by) and PhpStorm would only need to read what is written there.

0

Please sign in to leave a comment.