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 ?
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)
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.
$this->tabs[$key]
is a string, not an array.
You can't add an item to a string as if it was an array.
This will work without errors.
$this->tabs[$key] = array("name");
$this->tabs[$key][] = new OptionsElements();
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();