PHP 变量声明不正确

PHP Incorrect variable declaration

调试遗留代码时遇到一个奇怪的问题。遗留代码正在移至 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你会得到 Notice: Array to string conversion in /in/N2poP on line 6

所以在以前的版本中,您覆盖了完整的变量,并且初始的空字符串将会消失,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 中的空字符串中,您可以使用正则表达式来查找您应该重构以解决问题的所有位置。