dongpu1881 2012-02-28 02:02
浏览 56
已采纳

PHP:无法将Object分配给数组

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 ?

展开全部

  • 写回答

5条回答 默认 最新

  • duanchen9594 2012-02-28 02:05
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?