2016-06-28 34 views
0

後,我有這樣的方法:PHP - 非法偏移類型,is_array和is_object

public function setVariable($variable, $value = null) 
{ 
    $variables = json_decode($this->variables); 

    if(is_array($variable) || is_object($variable)) 
     foreach($variable as $key => $value) 
      if(in_array($key, $this->variableNames)) 
       $variables[$key] = $value; 
    else 
     $variables[$variable] = $value; 

    $this->variables = json_encode($variables); 
    $this->save(); 
} 

但是,如果我這樣調用方法:

setVariable(['test' => 'test', 'bla' => 'bla']) 

它返回此錯誤:

ErrorException in User.php line 60: 
Illegal offset type 

第60行是這一行:

$variables[$variable] = $value; 

但是,它爲什麼會返回錯誤? 我檢查$ variable是數組還是對象, 但是它會繼續返回這個錯誤。爲什麼?

+2

因爲你和php不同地考慮'else'。 –

回答

2

此代碼

if(is_array($variable) || is_object($variable)) 
    foreach($variable as $key => $value) 
     if(in_array($key, $this->variableNames)) 
      $variables[$key] = $value; 
else 
    $variables[$variable] = $value; 

for PHP是一樣的:

if(is_array($variable) || is_object($variable)) { 
    foreach($variable as $key => $value) { 
     if(in_array($key, $this->variableNames)) 
      $variables[$key] = $value; 
     else 
      $variables[$variable] = $value; 
    } 
} 

看到區別?這就是爲什麼使用{}展示你的真正需要:

if (is_array($variable) || is_object($variable)) { 
    foreach($variable as $key => $value) { 
     if(in_array($key, $this->variableNames)) { 
      $variables[$key] = $value; 
     } 
    } 
} else { 
    $variables[$variable] = $value; 
} 

也知道(感謝@FirstOne)是foreachstdClass object(當$variable爲對象)是無效的操作,將引發錯誤。

+0

這是在煩擾我。你可以檢查[我的評論](http://stackoverflow.com/questions/38084565/php-illegal-offset-type-after-is-array-and-is-object#comment63605497_38084565)?我的意思是,這段代碼不會給出_E \ _ERROR:type 1 - 不能使用stdClass類型的對象作爲array_? – FirstOne

+0

我的意思是 - 我__ will___提到。 –

+1

爲了豐富答案,看看這個例子:[** https://3v4l.org/1dZLv**](https://3v4l.org/1dZLv)。問題與op試圖改變值的部分有關(如'$ variables [$ key] = ..')。爲了像這樣使用它,[json_decode](http://php.net/manual/en/function.json-decode.php)調用應該包含'true'作爲第二個參數。所以'$ variables = json_decode($ this-> variables,true);'。 – FirstOne