Cannot use string offset as an array in php

前端 未结 10 871
南方客
南方客 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 06:55

    I was fighting a similar problem, so documenting here in case useful.

    In a __get() method I was using the given argument as a property, as in (simplified example):

    function __get($prop) {
         return $this->$prop;
    }
    

    ...i.e. $obj->fred would access the private/protected fred property of the class.

    I found that when I needed to reference an array structure within this property it generated the Cannot use String offset as array error. Here's what I did wrong and how to correct it:

    function __get($prop) {
         // this is wrong, generates the error
         return $this->$prop['some key'][0];
    }
    
    function __get($prop) {
         // this is correct
         $ref = & $this->$prop;
         return $ref['some key'][0];
    }
    

    Explanation: in the wrong example, php is interpreting ['some key'] as a key to $prop (a string), whereas we need it to dereference $prop in place. In Perl you could do this by specifying with {} but I don't think this is possible in PHP.

提交回复
热议问题