dongpu1881 2012-02-28 10: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 10: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条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题