8

If, for example, I have a class like this:

class Foo
{
   /**
    * @var array<string, array{name: string, age: int}>
    */
   private array $things;

   /**
    * @return array
    */
   public function getThings(): array
   {
      return $this->things;
   }
}

Then phpstan will give me something along the lines of Method Foo::getThings() return type has no value type specified in iterable type array.

Of course, I can resolve this by adding the array shape definition to the @return, but given that I've already defined this on the property, is there a way to avoid duplication here that I'm missing?

0

1 Answer 1

9

No. PHPStan does not read the method body like that to understand what it returns.

You can use local type aliases to reduce the duplication:

/** @phpstan-type Things array<string, array{name: string, age: int}> */
class Foo
{
   /**
    * @var Things
    */
   private array $things;

   /**
    * @return Things
    */
   public function getThings(): array
   {
      return $this->things;
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

awesome, thank you! As an aside question/opinion (for better understanding): do you think it would be a reasonable addition to phpstan? Or, could you foresee any problems with handling this sort of thing automatically?
@MarkG Funny enough, someone asked the same question recently. And the answer is no: github.com/phpstan/phpstan/discussions/… As it's mentioned, maybe Rector already can handle this automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.