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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?