2016-06-28 107 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