在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。
答案 0 :(得分:1)
尝试使用array_merge php函数。代码:
array_merge($this->settings, $input_settings);