Skip to content

Class scoping problem when define $this using @var #7886

Description

@yeganemehr

Bug report

PHPStan reports a false positive error in this scenario:

  1. Include another file in a class method.
  2. In that file, define $this explicitly using PHPDoc
  3. Access to a private/protected class member, Code running correctly but PHPStan detect an error.

This technique widely seen in scripts and template systems in order to make classes (mainly view classes) members accessible to their templates (HTML part).

Code snippet that reproduces the problem

I have this repo that make you check this bug faster:

git clone https://github.com/yeganemehr/phpstan-class-scoping-issue.git

but for sake of make everything documented, I put code snippets here:

file1.php

<?php
class A
{
    protected string $test1 = "successful";

    public function run(): void
    {
        require __DIR__ . "/file2.php";
    }

    private function test2(): string
    {
        return "successful";
    }
}

$obj = new A();
$obj->run();

file2.php

<?php

/**
 * @var A $this
 */
echo $this->test1 . PHP_EOL;
echo $this->test2() . PHP_EOL;

Reported Error:

 ------ -------------------------------------------- 
  Line   file2.php                                   
 ------ -------------------------------------------- 
  6      Access to protected property A::$test1.     
  7      Call to private method test2() of class A.  
 ------ --------------------------------------------

Expected output

It's a legit code and it's work in PHP with no error, so it's expecting from PHPStan to report no error about it.

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

PHPStan is now an essential tool for me and my colleagues.
Your work enable us to write better and more reliable codes.
Thank you ❤️

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions