Skip to content

"Null reference" inspection doesn't correctly handle "instanceof" statement #1580

Closed
@msarris

Description

The "Null reference" will mark a variable returned from a function (a static method at least, didn't test other functions or methods) as possible null, when the method never returns a null value. This is checked via an instanceof statement, but the inspection doesn't recognize or correctly handle this statement.

| Plugin | Php Inspections (EA Extended) 4.0.4.1 |
| Language level | PHP 7.2 |

Current behaviour

See the following code:

class A
{
    /**
     * @param A|null $a
     *
     * @return A
     */
    public static function create(A $a = null)
    {
        if ($a instanceof A) {
            return $a;
        }

        return new A();
    }

    public function foo()
    {
        print 'bar';
    }
}

function test()
{
    $a = A::create();

    $a->foo();
}

In the method test() the statement $a->foo(); will be marked with a warning "Null pointer exception may occur here". When you inspect the create method you can easily see that the method never returns null and the PhpDoc also documents this.

Expected behaviour

$a->foo() should not be marked with the warning "Null pointer exception may occur here".

When you change if ($a instanceof A) { into if ($a) { or if ($a !== null) { then the warning is not added and the inspection correctly identifies that create never returns null.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions