Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what way is my array index an 'Illegal string offset'?

Tags:

php

When "future-proofing" code by testing it on PHP 5.4, I get a warning I don't understand.

function __clone() {
  $this->changed = TRUE;
  foreach ($this->conditions as $key => $condition) {
    if (
    $condition['field']
    instanceOf QueryConditionInterface) {
      $this->conditions[$key]['field'] = clone($condition['field']);
    }
  }
}

I broke out $condition['field'] into its own row to reduce the amount of code to focus on. About that specific line, PHP has this to say

Warning: Illegal string offset 'field' in DatabaseCondition->__clone()

And I just can't see how 'field', is an illegal string offset. I'm guessing that I'm just missing something obvious, but if the community can't find a problem, I'll file a bug report.

I interpret the warning as "Under no circumstances is 'field' a valid key". This error would have made sense if I had tried to us for example an array as a key.

like image 964
Letharion Avatar asked Feb 17 '12 12:02

Letharion


1 Answers

Without more knowledge about the creation of the conditions array/iterator, I can only assume that you should first check if the offset exists.

if(isset($condition['field']) && $condition['field'] instanceOf QueryConditionInterface)

Using isset in this situation is enough and faster than array_key_exists, the only difference is, if $condition['field'] is NULL isset will return falls, array_key_exists will return true, cause the key exists. But because you only want to work on fields that are an instance of QueryConditionInterface, you will running fine with isset.

like image 135
Tobias Herkula Avatar answered Oct 04 '22 06:10

Tobias Herkula