不能在 php 中使用字符串偏移量作为数组

php
2022-08-30 11:07:43

我正在尝试使用示例php代码模拟此错误,但尚未成功。任何帮助都会很棒。

“不能将字符串偏移量用作数组”


答案 1

对于 PHP4

...这再现了错误:

$foo    = 'bar';
$foo[0] = 'bar';

对于 PHP5

...这再现了错误:

$foo = 'bar';

if (is_array($foo['bar']))
    echo 'bar-array';
if (is_array($foo['bar']['foo']))
    echo 'bar-foo-array';
if (is_array($foo['bar']['foo']['bar']))
    echo 'bar-foo-bar-array';

(实际上来自 bugs.php.net

编辑

那么为什么错误没有出现在第一个if条件中,即使它是一个字符串。

因为PHP是一种非常宽容的编程语言,我猜。我将用代码说明我认为正在发生的事情:

$foo = 'bar';
// $foo is now equal to "bar"

$foo['bar'] = 'foo';
// $foo['bar'] doesn't exists - use first index instead (0)
// $foo['bar'] is equal to using $foo[0]
// $foo['bar'] points to a character so the string "foo" won't fit
// $foo['bar'] will instead be set to the first index
// of the string/array "foo", i.e 'f'

echo $foo['bar'];
// output will be "f"

echo $foo;
// output will be "far"

echo $foo['bar']['bar'];
// $foo['bar'][0] is equal calling to $foo['bar']['bar']
// $foo['bar'] points to a character
// characters can not be represented as an array,
// so we cannot reach anything at position 0 of a character
// --> fatal error

答案 2

升级到 PHP 7 后,我能够重现它。当您尝试将数组元素强制放入字符串中时,它会中断。

$params = '';
foreach ($foo) {
  $index = 0;
  $params[$index]['keyName'] = $name . '.' . $fileExt;
}

更换后:

$params = '';

自:

$params = array();

我停止收到错误。我在这个错误报告线程中找到了解决方案。我希望这有帮助。


推荐