Skip to content

preg_match in match expression - variable might be undefined #10418

@uuf6429

Description

@uuf6429

Bug report

match expressions in PHP can make up as a decent pattern matching engine. Unfortunately it seems to confuse phpstan a bit.

Here are three similar cases, for side-by side comparison:

Might be related to #7705, not sure.

Code snippet that reproduces the problem

$subject = 'hello world';
$something = match (1) {
    preg_match('/(\d+)/', $subject, $match) => 'it is a number: ' . $match[1],
    preg_match('/(\w+)/', $subject, $match) => 'it is a word: ' . $match[1],
    default => 'it is...something',
};

Actual output

Variable $match might not be defined.

Expected output

phpstan warning was not expected

Did PHPStan help you today? Did it make you happy in any way?

Help - yes - it did catch quite a few non-trivial mistakes.
Happy, not so much - means I need to review my own stuff more often. 🙈 😅

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions