PHP:数组声明中的变量

标签 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 不希望我在以下情况时内联连接 $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/

相关文章:

php - 检查数据库中是否存在行,如果不存在则显示消息

javascript - 具有最小值和最大值的 jQuery 简单 slider

javascript - 如何调试用于 IE 代理设置的 Javascript proxy.pac 文件?

java - 在 jsp 页面中创建对象

mysql - 尝试重命名数据库时,为什么 mySQL 不给出 "{"的错误?

php - 使用 PHP Google_Client、Google_Service_Blogger 通过 API v3 列出 Blogger 帖子

iPhone 应用程序在连接到仪器的设备、未连接仪器和模拟器的设备上的行为有所不同

python - 在 Ruby 代码中放置单个断点

r - 什么时候使用“with”功能,为什么好呢?

php - 从数据库查询设置变量的更好方法