[英]PHP - Illegal offset type, after is_array and is_object
I have this method: 我有这种方法:
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();
}
But, if I call the method like this: 但是,如果我这样调用方法:
setVariable(['test' => 'test', 'bla' => 'bla'])
It return this error: 它返回此错误:
ErrorException in User.php line 60:
Illegal offset type
Line 60 is this line: 60行是这一行:
$variables[$variable] = $value;
But, why it return the error? 但是,为什么它返回错误? I check if $variable is array or object, But it continues return this error. 我检查$ variable是数组还是对象,但是它继续返回此错误。 Why? 为什么?
This code 这段代码
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 is the same as: 对于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;
}
}
See the difference? 看到不同? That's why use {}
to show what you really need: 这就是为什么使用{}
来显示您真正需要什么的原因:
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;
}
Also be aware (thanks to @FirstOne) that foreach
over stdClass object
(when $variable
is object) is invalid operation and will raise error. 还应注意(由于@FirstOne), stdClass object
上的foreach
(当$variable
为object时)是无效操作,并且会引发错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.