Skip to content

while-true-try: Variable might not be defined #10245

@homersimpsons

Description

@homersimpsons

Bug report

When using a try block inside a while (true), PHPStan fails to see the variable as defined.

For simple cases such as the following PHPStan correctly deduce that the variable is defined and its type:

<?php declare(strict_types = 1);

function produceInt(): int { return 1; }

while (true) {
	$a = produceInt();
	break;
}

\PHPStan\DumpType($a); // Dumped type: int

Code snippet that reproduces the problem

https://phpstan.org/r/fb9bc3ad-1256-46ae-beb5-24e918dd07f7

Expected output

<?php declare(strict_types = 1);

/**
 * @throws \Exception
 */
function produceInt(): int
{
	return 1;
}

while (true) {
	try {
		$a = produceInt();
		break;
	} catch (\Throwable) {}
}

\PHPStan\DumpType($a); // Dumped type: int

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

I think I cannot count the amount of issues that didn't reach production thanks to PHPStan. It also helps a lot when reviewing code as I can focus on the core logic instead of the possible mistakes here and there.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions