noverify icon indicating copy to clipboard operation
noverify copied to clipboard

Using undefined variable causes it to be "conditionally defined"

Open quasilyte opened this issue 4 years ago • 5 comments

Code Example

<?php

function f($cond) {
    if ($cond) {
        echo $x; // 1
    }
    echo $x; // 2
}

Actual Behavior

<critical> ERROR   undefined: Undefined variable: x at hello.php:5
        echo $x; // 1
             ^^
<critical> INFO    undefined: Variable might have not been defined: x at hello.php:7
    echo $x; // 2
         ^^

Expected Behavior

Variable should be reported as undefined twice.

quasilyte avatar Mar 20 '20 21:03 quasilyte

In PHP the mere act of accessing an undefined variable is defining that variable. So I would say the messages are somewhat correct actually.

YuriyNasretdinov avatar Mar 20 '20 21:03 YuriyNasretdinov

I checked it with error_reporting(E_ALL):

<?php

error_reporting(E_ALL);

function f($cond) {
    echo $x;
    echo $x;
}

f(true);

This code gives 2 run-time notices:

PHP Notice:  Undefined variable: x in hello.php on line 6
PHP Notice:  Undefined variable: x in hello.php on line 7
$ php -version
PHP 7.2.19-0ubuntu0.18.04.2 (cli)

quasilyte avatar Mar 20 '20 21:03 quasilyte

Interesting.

YuriyNasretdinov avatar Mar 20 '20 21:03 YuriyNasretdinov

I'm trying to find undefined variables behavior documentation, but can't find anything as of yet.

quasilyte avatar Mar 20 '20 21:03 quasilyte

The behaviour of undefined variables is, well... Undefined lol.

YuriyNasretdinov avatar Mar 20 '20 21:03 YuriyNasretdinov