简体   繁体   中英

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:

$variables[$variable] = $value;

But, why it return the error? I check if $variable is array or object, But it continues return this error. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM