我在獲取此函式的回傳型別時遇到問題,因為我在 switch 中有混合型別。我用過混合,它爆炸了。我使用了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;
}
}
ERROR 以下是錯誤
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.
uj5u.com熱心網友回復:
在現代 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 會對所有選項感到滿意。
uj5u.com熱心網友回復:
此 ERROR 是因為您沒有宣告要從中回傳的型別 getValue()
這就是你宣告回傳型別的方式
public function getValue(bool $typed = false): date
uj5u.com熱心網友回復:
您需要宣告函式的回傳型別。
簡單地宣告一個回傳型別,你需要:在引數后面放一個,像這樣
public function store(Request $request): JsonResponse
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/384962.html
