Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Fatal error: Unsupported operand types

Tags:

php

I keep getting the following error and I was wondering on how to fix?

Fatal error: Unsupported operand types in C:\wamp\www\tuto\core\Controller.php on line 23

Here is line 23.

$this->vars +=  $key;

Here is the full code below.

public function set($key,$value=null){

    if(is_array($key)){

        $this->vars +=  $key;

    }else{
        $this->vars[$key]= $value;
    }
}
like image 393
user3548898 Avatar asked Apr 18 '14 12:04

user3548898


2 Answers

+ can be used in different ways but to avoid complications, only use it on numeric values.

When you didnt initially set $this->vars to be an array, it won't work (thx to deceze); see http://codepad.viper-7.com/A24zds

Instead try init the array and use array_merge:

public function set($key,$value=null){
    if (!is_array($this->vars)) {
        $this->vars = array();
    }

    if(is_array($key)){
        $this->vars = array_merge($this->vars, $key);
    }else{
        $this->vars[$key] = $value;
    }
}

Examples:

<?php
$test = null;

$t    = array('test');

//$test += $t prints the fatal here

$test = array('one');

$test += $t;

// will only print '0 => one'
print_r($test);


$test = array_merge($test, $t);

// will print both elements
print_r($test);
like image 52
Daniel W. Avatar answered Oct 05 '22 19:10

Daniel W.


The solution is in the error. You are trying to sum two value that has different types. You are summing array with normal value;

$this->vars +=  $key;

$key shouldnt be an array

Or second option;

$this->vars should be an array

like image 33
Hüseyin BABAL Avatar answered Oct 05 '22 19:10

Hüseyin BABAL