PHP 8.0 如何在没有警告的情况下以简洁明了的方式将字符串附加到未知的 SESSION 变量
PHP 8.0 how to append strings to unknown SESSION variables in a clean concise way without Warnings
以前的代码在 PHP 7.4 中看起来像这样:
$_SESSION['message'] .= "Sorry; That file or location can not be found.";
这将附加到现有字符串或设置为新字符串的内容。我的错误日志(关闭通知)将是空的。
现在使用 PHP 8.0+,undefined array elements(除其他事项外)被归类为 警告 而不是通知。
PHP Warning: Undefined array key "message" in /index.php on line 29
我理解此 警告 背后的概念逻辑,但在上述代码的实例中,它需要一个冗长的解决方法;类似于:
if(array_key_exists('message', $_SESSION)){
$_SESSION['message'] .= "Sorry; That file or location can not be found.";
}
else {
$_SESSION['message'] = "Sorry; That file or location can not be found.";
}
或者可能;
$_SESSION['message'] = (array_key_exists('message', $_SESSION)?$_SESSION['message']:"")
."Sorry; That file or location can not be found.";
对于数十个网站上的数千个 SESSION 元素来说,这看起来真的很粗糙;更难阅读,而且通常会大篇幅地避免出现似乎毫无用处的警告消息。
我不想关闭警告消息。
是否有任何可能的解决方法;例如 php.ini 中的任何方式来避免此触发串联操作 (.=
) ?我们能否以某种方式转义系统变量(超全局变量)或更具体地说 SESSION
数据(可能还有 POST
数据),在连接之前不可能知道它的值。
更简洁的解决方法可以是:
$_SESSION['message'] = ($_SESSION['message'] ?? ''). " string here";
这可能是最好的了。
以前的代码在 PHP 7.4 中看起来像这样:
$_SESSION['message'] .= "Sorry; That file or location can not be found.";
这将附加到现有字符串或设置为新字符串的内容。我的错误日志(关闭通知)将是空的。
现在使用 PHP 8.0+,undefined array elements(除其他事项外)被归类为 警告 而不是通知。
PHP Warning: Undefined array key "message" in /index.php on line 29
我理解此 警告 背后的概念逻辑,但在上述代码的实例中,它需要一个冗长的解决方法;类似于:
if(array_key_exists('message', $_SESSION)){
$_SESSION['message'] .= "Sorry; That file or location can not be found.";
}
else {
$_SESSION['message'] = "Sorry; That file or location can not be found.";
}
或者可能;
$_SESSION['message'] = (array_key_exists('message', $_SESSION)?$_SESSION['message']:"")
."Sorry; That file or location can not be found.";
对于数十个网站上的数千个 SESSION 元素来说,这看起来真的很粗糙;更难阅读,而且通常会大篇幅地避免出现似乎毫无用处的警告消息。
我不想关闭警告消息。
是否有任何可能的解决方法;例如 php.ini 中的任何方式来避免此触发串联操作 (.=
) ?我们能否以某种方式转义系统变量(超全局变量)或更具体地说 SESSION
数据(可能还有 POST
数据),在连接之前不可能知道它的值。
更简洁的解决方法可以是:
$_SESSION['message'] = ($_SESSION['message'] ?? ''). " string here";
这可能是最好的了。