Cannot use string offset as an array in php

前端 未结 10 851
南方客
南方客 2020-11-29 06:35

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\"

10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 07:11

    For PHP4

    ...this reproduced the error:

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

    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';
    

    (From bugs.php.net actually)

    Edit,

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

    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
    

提交回复
热议问题