Skip to content

Bug: Trait used by two classes, checks for one class with properties but fails on the excluded second class #9386

@belisoful

Description

@belisoful

Bug report

A trait that checks for the class using it, and uses the checked class properties then throws an error in the SecondClass using the trait that is not part of the class check nor has those properties. The code is very straight forward but the description is not.

The problem is in the SecondClass that uses BaseTrait. For some reason PHPStan is continuing the branch with the class that doesn't have those properties and then fails when accessing those properties.

error:
Comparison operation ">=" between int and (array|float|int) results in an error.

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

trait BaseTrait {
	protected false|int $_pos;
	
	public function myMethod():bool {
		$pos = $this->_pos;
		if ($pos === false)
			return false;
		if (($this instanceof BaseClass) && $this->length !== null) //<- should only be BaseClass in this statement
			return $pos >= $this->offset + $this->length;  //. <- Error:  Comparison operation ">=" between int and (array|float|int) results in an error.
		return false;
	}
}

class BaseClass
{
	use BaseTrait;
	protected ?int $length = null;
	protected int $offset = 0;
}
class SecondClass
{
	use BaseTrait;
}

https://phpstan.org/r/84a3c6f1-9649-4f59-8a1b-ae9d8af656eb

Expected output

The expected output is NO ERROR. The length and offset are proper integers and the comparison is legitimate; not compared against float or array.

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

I am very happy with phpstan and the quick responses to bugs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions