PHP:数组声明中的变量

时间:2013-04-26 02:07:17

标签: php debugging syntax variable-assignment

我在PHP中工作并从foreach{}循环内部调用以下函数。此函数需要接受$subTheme作为选项参数,因为目的是避免不必要的代码重复(DRY,对吧?)。

所以,首先 - 这里的功能是:

/*
 * CSS needed to apply the selected styles to text elements.
 */
function this_site_text_css( $subTheme = '' ) {

    $GLOBALS['this_theme_mod']; // this is in global scope already

    $themeVarSuffix = $subTheme['var_suffix'];
    $themeClassName = $subTheme['class_name'];

    $content_bg_color  = $this_theme_mod['content_bg_color' . $themeVarSuffix ];
    $page_bg_color     = $this_theme_mod['page_bg_color' . $themeVarSuffix ];
    $primary_color     = $this_theme_mod['primary_theme_color' . $themeVarSuffix ];

    $css = 'body' . $themeClassName . '{ /* special classes */ };'

    return $css
}

还有更多的事情发生,但它相当乏味,只是将CSS连接起来作为返回的字符串。

这样被称为

$data = '';
$data .= this_site_text_css();
$subThemeArray = array(
  'theme_a' => array( 
     'var_suffix' => '_theme_a',
     'class_name' => '.theme-a',
  ),
  'theme_b' => array( 
     'var_suffix' => '_theme_b',
     'class_name' => '.theme-b',
  ),
);
foreach( $subThemeArray as $key => $theme ) {
   $data .= this_site_text_css( $theme );
}

我收到了PHP警告Illegal string offset 'class_name',我猜这是因为PHP在{{1}声明它时不希望我联接$themeVarSuffix内联}}。我非常确定这是一种方法,而且我已经搜遍过,也许我还没有找到合适的关键字,但任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:3)

  

非法字符串偏移'class_name'

...表示$subTheme实际上是string而不是array。发生这种情况是因为您在函数声明$subTheme = ''中有一个默认值,并且在调用它时错过了传递值,此处:

$data .= this_site_text_css();

所以$subTheme是一个空字符串,当然没有索引'class_name'。

答案 1 :(得分:1)

$subThemeArray数组中,应将theme_class索引称为class_name