PHPStan impure function that modifies a parent property

2 days ago 11
ARTICLE AD BOX

Given the code below, PHPStan reports an error that the comparison on line 36 always evaluates to true, making the return true statement unreachable. But if I run the code, the output is 'true'.

How can I prevent this error, assuming that I cannot modify the ExternalService and the input argument?

PHPStan Playground: https://phpstan.org/r/17ee1a74-50c3-4fe2-a284-dd15ca86f211

<?php declare(strict_types = 1); class Child { public ParentModel $parent; public function __construct(ParentModel $parent) { $this->parent = $parent; } } class ParentModel { public int $property = 0; public Child $child; public function __construct() { $this->child = new Child($this); } } class MyService { public function operate(ParentModel $model): bool { if ($model->property !== 0) { return false; } $externalService = new ExternalService(); $externalService->operate($model->child); if ($model->property !== 1) { return false; } return true; } } class ExternalService { /** * @phpstan-impure */ public function operate(Child $child): void { $child->parent->property = 1; } } var_dump((new MyService)->operate(new ParentModel()));
Read Entire Article