数组错误可能是 PHP 版本问题吗?

Is array error possibly a PHP version issue?

我在一个网站上工作,自去年 10 月以来,以下几行代码运行良好:

if(empty($post_types))  
{ 
  $post_types[] = 'post';         
  $post_types[] = 'product-list';
}

我以前在 PHP 中从未见过这种构造,(自从我开始使用 C 进行编程工作以来,这有点让人恼火),但它确实有效。

我们使用相同的技术和基本设置启动了第二个站点,该站点在相同的代码行中引发了以下错误,

"Uncaught Error: [] operator not supported for strings ..."

这些站点托管在同一个地方,但我注意到它们使用的是 PHP 的不同 7.x 版本。我做了一些研究,看看这种行为是否是由于 PHP 7.3 中的更改引起的,但我没有找到答案。

请注意,我的问题是这种情况是否可能是 PHP 版本问题,而不是如何解决数组问题,我将其更改为

$post_types = array('post', 'product-list');

我在 PHP 文档中找到了您的答案 Creating/modifying with square bracket syntax

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.

Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.

因此 PHP 7.1.0 似乎与您描述的问题相符。

在您的代码中,您的 $post_type 变量必须初始化为字符串 [编辑:我只能用空字符串重现问题],并且之前是( PHP < 7.1. 0) 静默转换为数组。