[英]PHP - Illegal offset type, after is_array and 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是数组还是对象,但是它继续返回此错误。 为什么?
这段代码
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;
对于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), stdClass object
上的foreach
(当$variable
为object时)是无效操作,并且会引发错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.