无法在PHP中将字符串偏移量用作数组 [英] Cannot use string offset as an array in php

查看:176
本文介绍了无法在PHP中将字符串偏移量用作数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to simulate this error with a sample php code but haven't been successful. Any help would be great.

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

"Cannot use string offset as an array"

推荐答案

对于PHP4

...这重现了错误:

For PHP4

...this reproduced the error:

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

对于PHP5

...这重现了错误:

For PHP5

...this reproduced the error:

$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 )

为什么错误不会出现在 首先,即使条件是 字符串.

so why doesn't the error appear in the first if condition even though it is a string.

我想,因为PHP是一种非常宽容的编程语言.我将用代码说明我的想法:

Because PHP is a very forgiving programming language, I'd guess. I'll illustrate with code of what I think is going on:

$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

这篇关于无法在PHP中将字符串偏移量用作数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆