Skip to content

Instantly share code, notes, and snippets.

@arturmamedov
Last active February 12, 2019 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturmamedov/12345cea305552e71a58f1e66e1b5746 to your computer and use it in GitHub Desktop.
Save arturmamedov/12345cea305552e71a58f1e66e1b5746 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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