2011-08-29 48 views
0

在jQuery中有$ .extend()函數。這基本上就像匹配默認設置和輸入設置一樣。那麼,我想在PHP中使用類似的技術,但似乎沒有類似的功能。所以我想知道:是否有與.extend()類似的功能,但在PHP中?如果不是那麼,有什麼替代品?如何將新變量與類中的默認變量進行匹配?

這是一個示例類,以及我目前如何獲得此效果。我還添加了一個評論,我怎麼會希望這樣做:

class TestClass { 
    // These are the default settings: 
    var $settings = array(
     'show' => 10, 
     'phrase' => 'Miley rocks!', 
     'by' => 'Kalle H. Väravas', 
     'version' => '1.0' 
    ); 
    function __construct ($input_settings) { 
     // This is how I would wish to do this: 
     // $this->settings = extend($this->settings, $input_settings); 

     // This is what I want to get rid of: 
     $this->settings['show'] = empty($input_settings['show']) ? $this->settings['show'] : $input_settings['show']; 
     $this->settings['phrase'] = empty($input_settings['phrase']) ? $this->settings['phrase'] : $input_settings['phrase']; 
     $this->settings['by'] = empty($input_settings['by']) ? $this->settings['by'] : $input_settings['by']; 
     $this->settings['version'] = empty($input_settings['version']) ? $this->settings['version'] : $input_settings['version']; 

     // Obviously I cannot do anything neat or dynamical with $input_settings['totally_new'] :/ 
    } 
    function Display() { 
     // For simplifying purposes, lets use Display and not print_r the settings from construct 
     return $this->settings; 
    } 
} 

$new_settings = array(
    'show' => 30, 
    'by' => 'Your name', 
    'totally_new' => 'setting' 
); 

$TC = new TestClass($new_settings); 

echo '<pre>'; print_r($TC->Display()); echo '</pre>'; 

如果您發現,有一個全新的設定:$new_settings['totally_new']。這應該只包含在數組內$this->settings['totally_new']。 PS:以上代碼輸出this

回答

1

嘗試使用array_merge php函數。代碼:

array_merge($this->settings, $input_settings); 
+0

我再次感到如此愚蠢。輝煌的答案! '$ this-> settings = array_merge($ this-> settings,$ input_settings);'做了超出我預期的技巧:)奇怪的是,就在大約一小時前,我的眼睛滑過array_merge函數^^。謝啦! –