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。
我再次感到如此愚蠢。辉煌的答案! '$ this-> settings = array_merge($ this-> settings,$ input_settings);'做了超出我预期的技巧:)奇怪的是,就在大约一小时前,我的眼睛滑过array_merge函数^^。谢啦! –