Brian
Brian

Reputation: 3958

PHP: Variable in array declaration

I'm working in PHP and calling the following function from inside a foreach{} loop. This function needs to accept $subTheme as an option parameter because the purpose is to avoid unnecessary code repetition (DRY, right?).

So, first off - here's the function:

/*
 * 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
}

There's more happening but it's rather tedious and just concatenates CSS as a string to return.

It's being called like this

$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 );
}

I'm getting a PHP warning Illegal string offset 'class_name' and I'm guessing this is because PHP doesn't want me to concatenate $themeVarSuffix inline when declaring it at $themeClassName. I'm pretty sure there's a way to do this, and I've searched all over, perhaps I haven't searched the right keywords, but any help would be appreciated.

Upvotes: 2

Views: 95

Answers (2)

raidenace
raidenace

Reputation: 12836

In $subThemeArray array the index theme_class should be called class_name

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158110

Illegal string offset 'class_name'

... means that $subTheme is actually a string and not an array. This happens because you have a default value for it in the function declaration $subTheme = '' and missed to pass a value once you call it, here:

$data .= this_site_text_css();

So $subTheme is an empty string which has of course no index 'class_name'.

Upvotes: 3

Related Questions