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

ram*_*mpr 33 php

我试图用示例PHP代码模拟这个错误,但没有成功.任何帮助都会很棒.

"不能将字符串偏移用作数组"

Bjö*_*örn 59

对于PHP4

......这再现了错误:

$foo    = 'bar';
$foo[0] = 'bar';
Run Code Online (Sandbox Code Playgroud)

对于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';
Run Code Online (Sandbox Code Playgroud)

(实际上来自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
Run Code Online (Sandbox Code Playgroud)

  • "为什么错误不会出现在第一个if条件中"?这是你的答案:在字符串上使用括号语法时,你定义的是偏移量,而不是键.因为它期望一个偏移量,括号内传递的任何内容都会立即转换为整数.如果取字符串"bar"并将其强制转换为整数,则结果将为整数,其值为0.这意味着0将作为偏移量传递.在字符串的偏移0处,我们有字母"b",因此返回"b".如果您使用一组额外的括号,PHP会将括号访问视为一个数组,因此会显示您的错误. (2认同)

小智 12

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

$params = '';
foreach ($foo) {
  $index = 0;
  $params[$index]['keyName'] = $name . '.' . $fileExt;
}
Run Code Online (Sandbox Code Playgroud)

更改后:

$params = '';
Run Code Online (Sandbox Code Playgroud)

至:

$params = array();
Run Code Online (Sandbox Code Playgroud)

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

  • 我想这应该是答案。我也犯过这个错误... (2认同)