PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 23, 2022

[FIXED] How can I avoid repetition of array shape declaration for method return value?

 November 23, 2022     php, phpstan     No comments   

Issue

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?


Solution

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;
   }
}


Answered By - Can Vural
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing