February 28, 2012

PHP : Cannot assign an Object to array

Question by Merianos Nikos

I have create the following class :

Main class file

class NativeTabs
{
    private $tabs = array();

    public function __construct()
    {
        require_once('/options_elements.php');
    }

    public function add_tab($key = '', $name = '')
    {
        // ...

        $this->tabs[$key] = $name;
        $this->tabs[$key][] = new OptionsElements();

        // ...

    }
}

$nt = new NativeTabs();
$nt->add_tab('tabname', "Tab Name");

options_elements.php File

class OptionsElements
{
    public function __construct()
    {
    }
}

And when I execute that code I get the following error :

Fatal error: [] operator not supported for strings in PATH/TO/MY/FILEnative_tabs.php on line THE_LINE_THAT_CONTAIN_THE_CODE($this->tabs[$key][] = new OptionsElements();)

Why I can’t assing the object in $this->tabs[$key][] ?

Any idea please ?

Answer by Nicola Peluchetti

You should do

$this->tabs[$key] = array();
 $this->tabs[$key][] = new OptionsElements();

otherwise you use [] with a string (you assigned $this->tabs[$key] = $name; on the line above so $this->tabs[$key] is a string)

Answer by Starx

This will work without errors.

$this->tabs[$key] = array("name");
$this->tabs[$key][] = new OptionsElements();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!