PhpStorm's support for generics in PHPDoc is improving, but as of 2024, it does not fully support advanced generic annotations like @template and @extends for array shapes in the same way that PHPStan or Psalm do. This means that, even though your code is correct for static analysis, PhpStorm's autocomplete and type inference may not work as expected for generics with array shapes.
Workarounds and Recommendations:
1. Use @return with Explicit Array Shape in Child Class
One practical workaround is to override the data() method in your child class (Foo) and use an explicit @return annotation with the array shape. This will make PhpStorm recognize the return type for autocomplete.
/**
* @extends BaseClass<array{id: int, name: string, name2: string, name3: string}>
*/
class Foo extends BaseClass
{
/**
* @return array{id: int, name: string, name2: string, name3: string}
*/
public function data(): array
{
return parent::data();
}
}
Now, when you call $foo->data(), PhpStorm should provide autocompletion for the array keys.
2. Use Helper Methods or Properties
If you want to avoid overriding methods, you can create a helper method or property in the child class with the correct PHPDoc:
class Foo extends BaseClass
{
/**
* @var array{id: int, name: string, name2: string, name3: string}
*/
private array $myData;
/**
* @return array{id: int, name: string, name2: string, name3: string}
*/
public function getMyData(): array
{
return $this->myData;
}
}
3. Track PhpStorm Updates
JetBrains is actively working on improving generics support. You can track their progress and vote for related issues here:
Summary
- PHPStan will understand your generics, but PhpStorm currently needs explicit
@returnannotations for autocomplete. - Override the method in the child class and specify the array shape in the PHPDoc.
- Keep your generics for static analysis, but use explicit types for IDE support.
Example usage:
$foo = new Foo();
$data = $foo->data();
// PhpStorm should now autocomplete $data['id'], $data['name'], etc.
In short:
For now, to get PhpStorm autocomplete for array shapes, you must specify the array shape in the
@returnannotation in the child class, even if you use generics for static analysis.