从存储在变量中的字符串中提取对象数据

7
当直接输入对象名称(类别),它会返回正确的值。例如:
 $primary = $this->dbmapper->category['primary'] ;  // ( Correct Output )

但是,当把对象名称存储在名为 $dataname 的变量中时,它会返回空白,例如:
 $dataname = 'category';
 $primary = $this->dbmapper->$dataname['primary'] ;   ( Blank Output )

我的构造函数变量是:

  $this->dbmapper = $this->mapper();

我的功能是:

  function mapper($module='')
    {
        $mapper =  array();
        $mapper['category']['table'] = 'allcategory';
        $mapper['category']['primary'] = 'categoryID';
        $mapper['page']['table'] = 'allpages';
        $mapper['page']['primary'] = 'pageID';
        return (object) $mapper;
    }
1个回答

5

如果要访问一个对象属性(特别是数组),可以通过变量用大括号括起来:

...
$dataname = 'category';
$primary = $this->dbmapper->{$dataname}['primary'];

可以用,谢谢。 - Alok Jha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接