In jQuery there is $.extend() function. That basically works like matching default settings with input settings. Well, I want to use similar technique in PHP, but it seems, that there is no similar function. So I'm wondering: Is there a similar function as .extend()
, but in PHP? If not then, what alternatives are there?
This is an example class and how I get this effect currently. I also added a comment, how I would wish to do this:
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_se开发者_Go百科ttings['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>';
If you notice, that there is a totally new setting: $new_settings['totally_new']
. That should just get included inside the array as $this->settings['totally_new']
. PS: Above code outputs this.
Try to use array_merge php function. Code:
array_merge($this->settings, $input_settings);
精彩评论