PHP 5 登录"syntax error, unexpected '?' "时使用??算子



此代码是登录表单的一部分,我想确保该字段不为空。当我使用这行代码时,出现以下错误:

syntax error, unexpected '?'

if(is_blank($admin['username'])) {
$errors[] = "Username cannot be blank.";
} elseif (!has_length($admin['username'], array('min' => 8, 'max' => 255))) {
$errors[] = "Username must be between 8 and 255 characters.";
} elseif (!has_unique_username($admin['username'], $admin['id'] ?? 0)) {
$errors[] = "Username not allowed. Try another.";
}

我知道我收到错误,因为我正在使用 PHP 5.5。

谢谢!

是的,您需要使用以下语句:

(isset($admin['id']) ? $admin['id'] : 0 )

由于 PHP5.5没有??null coalesce operator(PHP 7 及更高版本(,因此您需要执行老式的速记。

请不要把它放在括号之间,这样它就不会在里面失败 if or else 语句和/或函数。

您也可以使用

$admin['id'] ?: 0;

但这会在未设置$admin['id']时发出通知。

最新更新