具有定义类型的 php 7 函数返回与类型相关的错误

问题描述 投票:0回答:2

我的代码有问题:

declare(strict_types=1);

class TextModifications
{
    static public function readValue(string $string): string
    {
        return $purifier->purify($string);
    }

    static public function saveValue(string $string): string
    {
        return $string;
    }
}
$TextModifications = new TextModifications();
$TextModifications->saveValue($_POST["login"])

我有错误: 致命错误:Uncaught TypeError: Argument 1 passed to TextModifications::saveValue() must be the type string, null given, called in /Applications/XAMPP/xamppfiles/htdocs/1.php on line 21 and defined in /Applications/ XAMPP/xamppfiles/htdocs/1.php:11 堆栈跟踪:#0 /Applications/XAMPP/xamppfiles/htdocs/1.php(21): TextModifications::saveValue(NULL) #1 {main} throw in /Applications/XAMPP /xamppfiles/htdocs/1.php 第 11 行

我有 PHP 7.2.

有谁知道如何解决这个问题?

php php-7
2个回答
5
投票

似乎您将 NULL 作为第一个参数传递给需要字符串参数的函数。在调用函数之前检查变量

$_POST['login']
是否为 null 或接受 null 值。这取决于您想在哪里验证输入数据。


3
投票

除了 @Ezequielanswer 之外,如果您想允许处理

null
值作为
saveValue
函数的输入,您可以使用
?
string

会像下面这样:

static public function saveValue(?string $string): ?string
{
    return $string;
}

来自 PHP 文档

现在可以标记参数和返回值的类型声明 通过在类型名称前加上问号作为可空性。这 表示与指定的类型一样,NULL 也可以作为 参数,或分别作为值返回。

© www.soinside.com 2019 - 2024. All rights reserved.