Skip to content

Accessing readonly promoted property in a method defined above constructor produces error #7198

@gronostajo

Description

@gronostajo

Bug report

  1. Create a readonly promoted property.
  2. Add a trait that uses that property.
  3. Call trait method from the constructor.
<?php

trait TestTrait {
	public function foo(): void
	{
		$this->callee->foo();
	}
}

class TestCallee {
	public function foo(): void
	{
		echo "FOO\n";
	}
}

class TestCaller {
	use TestTrait;

	public function __construct(private readonly TestCallee $callee)
	{
		$this->foo();
	}
}

new TestCaller(new TestCallee());

Line 6: Access to an uninitialized readonly property TestCaller::$callee.

https://phpstan.org/r/c2519e6b-5e12-4a77-97ff-6c81de2b7dfa

Expected output

No errors. According to the RFC:

The forwarding property assignments occur at the start of the constructor. As such, it is possible to access both the parameter and the property in the constructor […]

In addition, if the trait is defined in a separate file (as would usually be the case), an additional issue manifests that adds to the confusion: the error is reported in the file of the class, but line number corresponds to the file of the trait.

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

I love PHPStan.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions