2013-04-26 58 views
2

我正在使用PHP並從foreach{}循環中調用以下函數。此功能需要接受$subTheme作爲選項參數,因爲其目的是爲了避免不必要的代碼重複(幹,是嗎?)。PHP:數組聲明中的變量

所以,第一關 - 這裏的功能:

/* 
* 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不希望我在$themeClassName聲明時,它串聯$themeVarSuffix內聯。我很確定有一種方法可以做到這一點,我搜遍了所有,也許我沒有搜索正確的關鍵字,但任何幫助,將不勝感激。

回答

3

非法串偏移 'CLASS_NAME'

...意味着$subTheme實際上是一個string而不是array。這是因爲你必須在函數聲明$subTheme = ''爲它的默認值,錯過了一次,你怎麼稱呼它,在這裏傳遞一個值:

$data .= this_site_text_css(); 

所以$subTheme是具有當然沒有索引「CLASS_NAME」的一個空字符串。

+1

謝謝!就是這樣......只需要做 'function this_site_text_css($ subTheme = array())' – Brian 2013-04-26 02:17:23

1

$subThemeArray數組索引theme_class應該叫class_name

+0

+1好了!對於其他人,請注意問題在此答案後更新。 – hek2mgl 2013-04-26 02:18:00

+0

我很欣賞這一點 - 但我只是寫了一些僞代碼,所以我最初發布的不正確的代碼與我的工作代碼不同,工作代碼從不錯,只是僞代碼。 – Brian 2013-04-26 02:30:51

+0

np,事情是,當代碼發佈用於調試時,永遠不能確定什麼是錯字,什麼是代碼中的真正bug。反正很高興@ hek2mgl知道了你的想法 – raidenace 2013-04-26 02:37:14