Skip to content

Detect accessing static property as non static #12692

@jnoordsij

Description

@jnoordsij

Feature request

In PHP, accessing a static (class) property in a non static way is not allowed, emitting a notice of this fact followed by a warning about a non-existing property. See also https://www.php.net/manual/en/language.oop5.static.php#language.oop5.static.properties. It would be nice for PHPStan to detect and report such usage, similarly to how it does so for the 'opposite' case (accessing a non static property in a static way).

This is particularly useful for when one is refactoring code and switching parts from static to non-static. Moreover, in some frameworks like Laravel the PHP notices/warnings are globally converted into exceptions, which may make the results quite harsh on developers.

I created an example at https://phpstan.org/r/fca513a1-a570-490d-a1ef-3bc0075e63df, that showcases:

  • a correct class method that does what it is supposed to do
  • a static class method that incorrectly statically accesses a non-static property, triggering a PHP fatal error, which is reported by PHPStan as incorrect
  • a nonStatic class method that incorrectly non-statically accesses a static property, triggering a PHP notice followed by a warning and then proceeds to potentially unexpected behavior

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

I was actually surprised to find out this isn't already spotted in some way, given all of my mistakes it manages to correct on a regular basis, so I'd say that's a compliment! ;)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions