Skip to content

PHPStan incorrectly inferes the type of values when spreading an object. #13144

@azjezz

Description

@azjezz

Bug report

Spreading an ArrayAccess object is allowed just like spreading an array, and the yielded values are of type V where V is the value type of ArrayAccess implementation.

PHPStan correclty inferes the type when using the array access syntax like this:

<?php

$arr = new ArrayObject(['a' => 1, 'b' => 2]);

PHPStan\dumpType($arr); // correctly inferred as `ArrayObject<string, int>`

$a = $arr['a']; // ok
$b = $arr['b']; // ok

PHPStan\dumpType($a); // correctly inferred as `int|null`
PHPStan\dumpType($b); // correctly inferred as `int|null`

but when spreading the object in an assignment, the resulting type of the values is incorrectly set to mixed.

Example:

<?php

$arr = new ArrayObject(['a' => 1, 'b' => 2]);

PHPStan\dumpType($arr); // correctly inferred as `ArrayObject<string, int>`

['a' => $a, 'b' => $b] = $arr; // ok, no issues are emitted

PHPStan\dumpType($a); // incorrectly inferred as `mixed`
PHPStan\dumpType($b); // incorrectly inferred as `mixed`

Code snippet that reproduces the problem

https://phpstan.org/r/e7c526a8-0d27-4626-a3f3-313e8c8c940b

Expected output

The type of $a and $b in the second example should be int or int|null

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

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions