1

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 ?

4
  • 1
    $this->tabs[$key] references a String, not an Array. Commented Feb 28, 2012 at 10:05
  • Oh now i see !!! I am so shy :( Commented Feb 28, 2012 at 10:06
  • Why you put require_once statement in NativeTabs constructor? Commented Feb 28, 2012 at 10:19
  • And why not ? Is that bad ? :? Commented Feb 28, 2012 at 10:22

5 Answers 5

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2

$this->tabs[$key] is a string, not an array.

You can't add an item to a string as if it was an array.

Comments

1

Why should you be able to assign that?

$this->tabs[$key] = $name;

Judging by the name you just set the array element to a string. Then you try to append an array element to this string? That won't work.

Comments

1

This will work without errors.

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

Comments

1

See inline.

$this->tabs[$key] = $name;
// $this->tabs[$key] becomes a string that contains $name
$this->tabs[$key][] = new OptionsElements();
// $this->tabs[$key][] has no meaning here as its neither array nor an unset value. 
// if it was unset or not declared PHP would have make it an array.

You could you the following.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.