【问题标题】:PHP : Cannot assign an Object to arrayPHP:无法将对象分配给数组
【发布时间】:2012-02-28 10:02:00
【问题描述】:

我创建了以下类:

主类文件

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 文件

class OptionsElements
{
    public function __construct()
    {
    }
}

当我执行该代码时,我收到以下错误:

致命错误:PATH/TO/MY/FILEnative_tabs.php 中的字符串不支持 [] 运算符 THE_LINE_THAT_CONTAIN_THE_CODE($this->tabs[$key][] = new OptionsElements();)

为什么我不能在$this->tabs[$key][] 中分配对象?

有什么想法吗?

【问题讨论】:

  • $this->tabs[$key] 引用的是字符串,而不是数组。
  • 哦,现在我明白了!我好害羞:(
  • 为什么你把require_once语句放在NativeTabs构造函数中?
  • 为什么不呢?那不好吗 ? :?

标签: php arrays oop


【解决方案1】:

你应该这样做

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

否则,您将 [] 与字符串一起使用(您在上面的行中分配了 $this->tabs[$key] = $name;,因此 $this->tabs[$key] 是一个字符串)

【讨论】:

    【解决方案2】:

    $this->tabs[$key] 是一个字符串,而不是一个数组。

    您不能将项目添加到字符串中,就像它是一个数组一样。

    【讨论】:

      【解决方案3】:

      为什么你应该能够分配它?

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

      根据您刚刚将数组元素设置为字符串的名称来判断。然后你尝试将一个数组元素附加到这个字符串?那是行不通的。

      【讨论】:

        【解决方案4】:

        这将不会出错。

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

        【讨论】:

          【解决方案5】:

          见内联。

          $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.
          

          你能做到以下几点。

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-10-20
            • 2010-11-22
            • 2017-12-10
            • 1970-01-01
            • 1970-01-01
            • 2011-06-06
            • 2017-05-02
            • 2015-07-15
            相关资源
            最近更新 更多