2012-10-07 71 views
0

我想創建一個更聰明的方式來創建if語句。我正在寫一個函數來做到這一點:智能如果語句和數組不工作

if (! function_exists('get_meta')) { 
    function get_meta($i) { 
     $fname_name = array(
        'copyright_text', 
        'about_name', 
        'archive_name', 
        'contact_name', 
        'lenguage_name', 
        'cc_name', 
        'about_link', 
        'archive_link', 
        'contact_link', 
        'lenguage_link', 
        'cc_link', 
        'about_editors_name', 
        'about_responsibility_name', 
        'about_joinus_name', 
        'about_editors_link', 
        'about_responsibility_link', 
        'about_joinus_link' 
        ); 
     foreach($fname_name as $fname) 
      include_once(get_option($fname)); 

     if ($i) return $fname_name[$i]; 
    } 
} 

但是,當這個函數被調用,它返回此錯誤:

Warning: include_once() [function.include]: Failed opening 'what' for inclusion (include_path='.;php\PEAR') in local\wp-content\themes\net\0.6\functions.php on line 398

基本上,只想補充get_option('');每個陣列,換來例如:

get_option('copyright_text'); 

甚至更​​具體的,返回:

get_option('copyright_text', ''); 

修復:

好吧,我只是自己解決這個問題,但我很感激這裏的任何建議。

而不是使用foreachinclude_once,我用一個更簡單的解決方案:

if ($i) return get_option($fname_name[$i], ''); 
else if ($i == 0) return get_option($fname_name[0], ''); 
+3

還有一個問題,那是顯而易見:你回來'$ FNAME [$ i]',當在這一點上不存在名爲'$ fname'的變量。 – NullUserException

+2

如何定義'get_option()'?或者更好的問題,你想在這裏做什麼?這個代碼有一個難聞的氣味。 – NullUserException

+0

我想將echo json_encode(get_option($ fname))添加到該foreach語句中,以查看get_option返回的內容。 –

回答

0

使用本

foreach($fname_name as $fname){ 
     include_once(get_option($fname)); 
     if ($i) return $fname; 
} 
0

這就像你正在創建寫存取方法的快捷方式。你會自己做一些好看的,看看PHP的魔術方法。特別要注意__get,__set和__call。

http://php.net/manual/en/language.oop5.magic.php

在這種情況下,你在做什麼長相類同如下:

class myClass { 

    // This could be associated with whatever other data you are interested in 
    private $_meta = array(
       'copyright_text', 
       'about_name', 
       'archive_name', 
       'contact_name', 
       'lenguage_name', 
       'cc_name', 
       'about_link', 
       'archive_link', 
       'contact_link', 
       'lenguage_link', 
       'cc_link', 
       'about_editors_name', 
       'about_responsibility_name', 
       'about_joinus_name', 
       'about_editors_link', 
       'about_responsibility_link', 
       'about_joinus_link' 
       ); 

    public function __get($name) { 
     if (in_array($name, $this->_meta)) { 
      return $this->_meta[$name]; 
     } 
    } 
}