-1

我在获取此函数的返回类型时遇到问题,因为我在开关中有混合类型。我用过混合的,它爆炸了。我使用了string|bool和几种类型的联合类型。

* @param  $value 
* @param  string $type

public function __construct(string $type,  $value)
    {  
        $this->type    = $type;
        $this->value   = $value;
    }

我已经尝试了所有方法,但没有通过 CI/CD 管道 (AWS)

public function getValue(bool $typed = false)
    {
        if (false === $typed) {
            return $this->value;
        }

        switch ($this->type) {
            case 'boolean':
                return (bool) $this->value;
            case 'datetime':
                if (empty($this->value)) {
                    return null;
                }

                return new \DateTime($this->value);
            case 'option_tags':
                return json_decode($this->value);
            default:
                return $this->value;
        }
    }

错误 以下是错误

  Method App\Model\Resources::getValue() has no return typehint specified.  
  Parameter #1 $time of class DateTime constructor expects string, string|true given.                                 
  Parameter #1 $json of function json_decode expects string, bool|string given.
4

3 回答 3

1

在现代 PHP 中,您可以提供所有可能类型的列表:

// Tweak type list your exact needs
public function getValue(bool $typed = false): bool|DateTime|null

...或者mixed如果该方法确实可以返回任何内容,则使用:

public function getValue(bool $typed = false): mixed

在旧版本中,您只能在 docblock 中使用@return标签:

/**
 * @param bool $typed
 * @return mixed
 * @throws Exception
 */

我了解 PHPStan 会对所有选项感到满意。

于 2021-12-18T09:22:11.210 回答
0

这个错误是因为你没有声明你想要返回的类型getValue()

这是您声明返回类型的方式

public function getValue(bool $typed = false): date
于 2021-12-18T02:34:04.173 回答
0

您需要向函数声明返回类型。

简单地声明一个返回类型,你需要:在参数之后放一个,像这样

public function store(Request $request): JsonResponse
于 2021-12-18T02:44:16.603 回答