调试遗留代码时我遇到了一个奇怪的问题。遗留代码正在移至 PHP 7.2。我不知道它最初是为哪个版本的 PHP 编写的,但它确实适用于 PHP 5.6。
下面是我的问题示例...
$variable = '';
$variable['key'] = 'Hello World!';
echo $variable['key'] // H
当我回显 $variable['key']
时,它只会从值中获取第一个字符。我现在知道这是因为 $variable
最初声明为字符串。
但为什么这在 PHP 5.6 中有效?我该怎么做才能在 7.2 中完成这项工作而不需要翻阅数千行代码?
是否有像 strict_types
这样的指令我可以使用?
最佳答案
来自 php.net
Warning Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Only the first character of an assigned string is used. As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly, it assigned a NULL byte.
http://php.net/manual/en/language.types.string.php#language.types.string.substr
所以“key”被转换为0,并且设置了第一个字符。 因为这是一个 char 类型,所以只从给定的字符串中设置“H”。
$variable = '';
$variable['key'] = 'Hello World!';
echo $variable;
echo $variable['key'];
如果您将代码更改为上面的代码,您可以更清楚地看到发生了什么。
因此文本“ello World!”在 PHP >= 7.1 中已丢失,因为您设置了第一个字符,类型保持为 string
。
在 php 5.6 中你会得到
注意:第 6 行/in/N2poP 中数组到字符串的转换
所以在以前的版本中,您覆盖了完整的变量,并且初始的空字符串将会消失,PHP 只是创建一个新数组。这种行为只发生在空字符串上!
文档中也提到了这一点: http://php.net/manual/en/language.types.string.php#language.types.string.substr
Note: As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal error. Formerly, the empty string was silently converted to an array.
最简单的解决方案是删除 $variable = '';
部分,它无论如何都是无效的,并且从未在您的遗留代码中使用过。或者将其替换为 $variable = [];
因为此行为只发生在 php < 7.1 中的空字符串中,您可以使用正则表达式来查找您应该重构以解决问题的所有位置。
关于PHP 不正确的变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53341454/