在 PHP 中的注释中指定 return 值

Specifying return value in annotation in PHP

假设我希望我的函数 return 为 null 或数组。如果我添加数组可能值可以吗?

/**
 * @return null|array{
 *     md5: ?string,
 *     data?: array,
 *     size?: ?string,
 *     bit_rate?: ?string,
 *     remote?: ?string,
 *     url?: ?string,
 *     body?: ?string,
 *     refresh?: bool,
 *     refreshRate?: int,
 *     data?: array{
 *         playlist?: array,
 *         repeat?: array,
 *         width?: int,
 *         height?: int,
 *         compression?: mixed,
 *         depth?: int,
 *         alpha_channel?: int,
 *         orientation?: string,
 *         url?: string,
 *     }
 * }
 */

github 上有一个问题描述了这个问题。 issue

使用该功能的一些代码:

/**
 * @return null|array{
 *     md5: ?string,
 *     data?: array,
 *     size?: ?string,
 *     bit_rate?: ?string,
 *     remote?: ?string("remote", "local"), // documents possible return values
 *     url?: ?string,
 *     body?: ?string,
 *     refresh?: bool,
 *     refreshRate?: int,
 *     data?: array{
 *         playlist?: array,
 *         repeat?: array,
 *         width?: int,
 *         height?: int,
 *         compression?: mixed,
 *         depth?: int,
 *         alpha_channel?: int,
 *         orientation?: string,
 *         url?: string,
 *     }
 * }
 */
function getInfo(): ?array {
    return [
        'md5' => md5('some info'),
        'url' => 'https://example.com/something',
        'data' => [],
        'remote' => 'remote' // possible values `remote` or `local`
    ];
}

我认为最好的选择是在函数描述中记录数组:

/**
 * Returns information about audio source
 *
 * Returns
 * array['md5']            null|string  md5 hash of something
 * array['size']?          null|string  size of audio (should be numeric)
 * array['bit_rate']?      null|string  bit rate
 * array['remote']?        null|string  is it a remote source possible values: "remote", "local" (should be bool)
 * array['url']?           null|string  remote url
 * array['body']           null|string  stream body
 * array['refresh']?       bool         some option
 * array['refreshRate']    int          refresh rate
 * array['data']?          array        audio data
 *      ['playlist']?      array        some playlist data
 *      ['repeat']?        array        some repeat data
 *      ['width']?         int          width of something
 *      ['height']?        int          height of something
 *      ['compression']?   mixed        some compression data
 *      ['delth']?         int          depth value
 *      ['alpha_channel']? int          alpha channel value
 *      ['orientation']?   string       some orientation data
 *      ['url']?           string       url of something
 *
 * @return null|array see above
 */