Skip to content

Closure defined in static method errors on $this, even if rebound later. #9765

@Crell

Description

@Crell

Bug report

When a closure is created, whether or not a $this inside is is legal seems to depend only on if there is a valid $this at the declaration site. However, closures are allowed to be rebound to a new object (or an object in the first place), making them valid. PHPStan doesn't seem to recognize this, and it's not clear how one would teach it to do so.

This is a common pattern in, for instance, PHPUnit data providers, which are static methods; if one of the test parameters returned is a closure (I do this quite often), and that closure calls $this->whatever() (which will be valid after it is bound later), PHPStan will error despite the code being valid.

Code snippet that reproduces the problem

https://phpstan.org/r/8f4da2b0-e93b-4e00-87c0-069e000e82a8

Expected output

The only error reported above that's legit is the warning that bindTo() may return null. The other two issues are misreported, since the closures is bound to an object before it is executed.

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

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions