Skip to content

PHPStan assume function that return value can't mutate class property #4301

@noemi-salaun

Description

@noemi-salaun

Bug report

When I set a property, then call a function that mutate that property and finally check the property value with a if statment, PHPStan think that my property still have the original value, but only if the function return something.

Code snippet that reproduces the problem

class HelloWorld
{
	private bool $foo;
	
	public function theMethod(): int {
		$this->foo = true;
		
		//$this->changeFoo();             // <-- NO ERROR with the return void method
		$this->changeFooWithReturn();     // <-- ERROR with the return int method
		
		if ($this->foo) {     // <-- PHPStan error : "If condition is always true."
			return 1;
		}
		
		return 0;
	}
	
	public function changeFoo(): void
	{
		$this->foo = false;
	}
	
	public function changeFooWithReturn(): int
	{
		$this->foo = false;
		return 0;
	}
}

https://phpstan.org/r/f711eb37-04be-42c9-bbfd-c79515b0e919

Expected output

PHPStan should not detect any issue here

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions