Last active
February 12, 2019 10:34
-
-
Save arturmamedov/12345cea305552e71a58f1e66e1b5746 to your computer and use it in GitHub Desktop.
Merge $defaults with custom passed $options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And with jQuery:
// [EN] ... so our
options
passed each time have priority overdefaults
defined here in function// and if we miss it no problem,
defaults
work for us