我正在使用 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 不希望我在以下情况时内联连接 $themeVarSuffix
在 $themeClassName
处声明它。我很确定有一种方法可以做到这一点,并且我已经搜索了所有内容,也许我没有搜索到正确的关键字,但任何帮助将不胜感激。
最佳答案
Illegal string offset 'class_name'
... 意味着 $subTheme
实际上是一个 string
而不是 array
。发生这种情况是因为您在函数声明 $subTheme = ''
中有一个默认值,并且在调用它时错过了传递值,如下所示:
$data .= this_site_text_css();
所以 $subTheme
是一个空字符串,当然没有索引“class_name”。
关于PHP:数组声明中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16227643/