首页 > 解决方案 > PHP数组坏了?$输出=''; $输出['id']

问题描述

以下代码适用于 PHP 7.0.33,但停止适用于 PHP 7.1.33:

    $output = '';
    foreach ($this->fields as $field) {
        if ($field == 'id') {
            $output['id'] = $event->get('id');
        } elseif (in_array($field,$this->properties)) {
            if (isset($properties[$field])) $output[$field] = $properties[$field];
        } elseif ($field == 'allDay') {
            $output[$field] = (bool) $event_arr[$field];
        } else {
            $output[$field] = $event_arr[$field];
        };
    }

在 PHP 7.0.33 中,它使用来自框架的值创建一个数组,但在 PHP 7.1.33 中 $output 只包含一些任意值。

这是 $output=''; 一个数组声明,因为这种数组样式访问 $output['id']=... ?

或者 PHP 7.0 和 7.1 之间是否存在破坏性数组更改?

请注意:代码摘自使用的开源插件,不是我写的,而且我无法回答为什么选择这个设计。关于这个设计决定的所有问题都是绝对正确的。我只是不知道可以创建这样的数组。当然,将这段代码转换为更常见的数组声明是有意义的。

标签: php

解决方案


是的,有一个向后不兼容的变化,它说自从 php7.1

写入超出范围的偏移量用空格填充字符串,其中非整数类型转换为整数,并且仅使用分配字符串的第一个字符。以前(即在 ph7.0 中),空字符串被默默地视为空数组。

更多信息与示例在这里:https ://www.php.net/manual/en/migration71.incompatible.php#migration71.incompatible.empty-string-modifcation-by-character 。

而且您还应该回答评论中的问题-如果您将$output其视为数组,那么为什么 $output将其定义为string


推荐阅读