Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Merge $defaults with custom passed $options
<?php
/*
* spesso abbiamo bisogno di parametri default obbligatori
* ma che possono essere sovrascritti con quelli custom passati alla funzione ad ogni chiamata
* ... la suluzione in 4 righe e' questa
* ---
* [EN] often we need a mandatory options parameters that can be overriden by custom params passed each time
* the solution is here in 4 rows of code
*/
// ...
/**
* Passiamo un array $options di default vuoto
* Che verra riempito con i valori default se intoccato
*
* Ma se alla chiamata di someMethod(1, 2, ['width' => '130px']) passiamo qualcosa nell'array
* allora prevalera lui come volore!
*/
public function someMethod($param1, $param2, $options = array())
{
// [EN] initialize the default options
$defaults = array(
'width' => null,
'height' => '130px',
);
// [EN] merge defaults and custom by overwrite if they isset
foreach($defaults as $k => $v){
$options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
}
// [EN] ... so our $options passed each time have priority over $defaults defined here in function
// and if we miss it no problem, default work for us
}
@arturmamedov

This comment has been minimized.

Copy link
Owner Author

arturmamedov commented Feb 12, 2019

And with jQuery:

$.fn.gdivMessage = function (param1, param2, options) {
    // [EN] initialize the default options
    var defaults = {
        autohide: true, 
        hidetime: 4000
    };

    // [EN] merge defaults and custom by overwrite if they isset
    var opts = $.extend(defaults, options);
...
});

// [EN] ... so our options passed each time have priority over defaults defined here in function
// and if we miss it no problem, defaults work for us

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.