Skip to content

Assigning properties via foreach is not detected as write access #9213

@derrabus

Description

@derrabus

Bug report

Given a class has a property that is only assigned to from the head of a foreach loop, PHPStan complains that the property "is never written, only read".

Code snippet that reproduces the problem

class IterateSomething
{
	/** @var string|null */
	private $currentKey;

	/** @var string|null */
	private $currentValue;

	/** @param iterable<string, string> $collection */
	public function __construct(private iterable $collection) {}

	public function printAllTheThings(): void
	{
		foreach ($this->collection as $this->currentKey => $this->currentValue) {
			echo "{$this->currentKey} => {$this->currentValue}\n";
		}
	}
}

https://phpstan.org/r/6b872005-bf5c-40f7-981d-15908e312d4f

Expected output

No errors

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

I've found a bug in my code! ❤️

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions