在PHP DocBlock中描述包含@phpstan-return的stdClass对象的数组? – PHPStan

huangapple go评论55阅读模式
英文:

Describe an array containing an object (stdClass) with @phpstan-return in PHP DocBlock? - PHPStan

问题

/**
 * @phpstan-return array{
 *     id: int,
 *     title: string,
 *     authors: stdClass{
 *         firstName: string,
 *         lastName: string,
 *     },
 * }
 */
英文:

I have an example function in PHP (8.2) that returns an array. Inside this array there is also an object, more precisely stdClass.

I use PHPStan as a static analyzer tool. How can I specify this (object shapes) structure syntactically correct to use it in @phpstan-return using PHPStan Array shapes ?

The example function getBooks():

function getBook(): array
{
    $author = new stdClass();
    $author->firstName = 'John';
    $author->lastName = 'Doe';

    return [
        'id' => 12345,
        'title' => 'Whoever may help me deserves a big "Thank You!"',
        'authors' => $author,
    ];
}

What I already tried and is an invalid syntax:

/**
 * @phpstan-return array{
 *     id: int,
 *     title: string,
 *     authors: object{
 *         firstName: string,
 *         lastName: string,
 *     },
 * }
 */

What I definitely already know is, that the object { .. } part is the syntactically incorrect one here.

答案1

得分: 2

截至 PHPStan 1.10.12,现在可以实现以下功能:

https://phpstan.org/writing-php-code/phpdoc-types#object-shapes

所以,对于你的情况,可以这样编写:

/**
 * @return object{
 *     id: int,
 *     title: string,
 *     authors: object{
 *         firstName: string,
 *         lastName: string,
 *     },
 * }
 */
英文:

As of PHPStan 1.10.12 this is now possible:

https://phpstan.org/writing-php-code/phpdoc-types#object-shapes

So, for your case, that would be written:

/**
 * @return object{
 *     id: int,
 *     title: string,
 *     authors: object{
 *         firstName: string,
 *         lastName: string,
 *     },
 * }
 */

答案2

得分: 0

/** @return array<string, int|stdClass|string> */
function getBook(): array
{ ... }
/** @return array<mixed> */
function getBook(): array
{ ... }
英文:

You can define the associative array architecture with the array&lt;keyType, valType|valType|...&gt; pattern:

/** @return array&lt;string, int|stdClass|string&gt; */
function getBook(): array
{ ... }

<kbd><strong>PHPStan demo</strong></kbd>

or specify that it is a mixed array:

/** @return array&lt;mixed&gt; */
function getBook(): array
{ ... }

huangapple
  • 本文由 发表于 2023年3月3日 21:55:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定