Skip to content

Catch use of $$this #4710

Closed
phpstan/phpstan-src
#5871

Description

@ancarda

Feature request

A colleague of mine caught a bug that used $$this->methodCall(). I know the phpstan/phpstan-strict-rules plugin can ban the use of $$, however I think PHPStan, out of the box, should prohibit $$this. Given $this always refers to an instance of a class, and not a string, it can't possibly be used as the lookup for something on the symbol table.

I played around with this in 3v4l.org, $$this just produces NULL, which PHPStan (0.12.81) does not pickup on to stop the method call. Consider the following code (available at https://3v4l.org/mhr52):

<?php

declare(strict_types=1);

final class Greeter
{
    public function greet(): void
    {
        echo $$this->greetText();
    }

    public function greetText(): string
    {
        return 'Hello World';
    }
}

$g = new Greeter();
$g->greet();

You will get the following PHP error when trying to run:

Fatal error: Uncaught Error: Object of class Greeter could not be converted to string in /in/mhr52:9

However, PHPStan (with --level=max) will not report any issues.

Activity

  1. ancarda commented on Mar 17, 2021

    @ancarda
    Author

    After further experimentation, it seems this would work if you have __toString, so perhaps PHPStan could check for that method's existence, and if it's not defined, reject $$this?

  2. ondrejmirtes commented on Mar 17, 2021

    @ondrejmirtes
    Member

    Hi, this is very easy to implement.

    • Have a rule that listens to Variable AST node
    • Get the $scope->getType($variable->name) when $variable->name is Expr
    • If $type->toString() is ErrorType, report the error.
  3. ancarda commented on Mar 17, 2021

    @ancarda
    Author

    Thank you @ondrejmirtes! I'll give it a go tonight. I'd love to be able to finally contribute something to PHPStan!

  4. ondrejmirtes commented on Mar 20, 2021

    @ondrejmirtes
    Member

    There's also the opportunity to catch the same problem with $foo->{$method}() etc.

  5. phpstan-bot commented on Sep 20, 2026

    @phpstan-bot
    Contributor

    Closed via merging phpstan/phpstan-src#5871

  6. github-actions commented on Oct 22, 2026

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

  7. locked as resolved and limited conversation to collaborators on Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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