Skip to content

Continue in a switch default should satisfy a null check #2549

@leongersen

Description

@leongersen

Bug report

This is perhaps in line with checking for unreachable code after a while loop as added in 0.11.16.

A continue in a default statement should be able to satisfy that a variable is always set to a non-null value if all branches of the switch set the variable. When using return instead (functionally identical in the example below), no errors are reported.

Code snippet that reproduces the problem

https://phpstan.org/r/68f10541-7684-4184-beed-7bcf2ab4e12f

class Pear {
	public function eat(): void {}
}

function test(): void {

	$apples = [1, 2, 3];

	foreach($apples as $apple) {
		$pear = null;

		switch(true) {
			case true:
				$pear = new Pear();

				break;

			default:
				// with a `return` here, no issues are reported
				continue 2;
		}

		// $pear is either set in the switch, or this code is not reached
		$pear->eat();
	}
}

test();

Expected output

I'd expect no errors here, but PhpStan reports:

+-----------------------------------------------+
| Line | test.php                               |
+-----------------------------------------------+
| 23   | Cannot call method eat() on Pear|null. |
+-----------------------------------------------+

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions