What is the best practice for defining a default/fallback value for an array?
description:
My function accepts 2 parameters. One of them is an array of options to choose from. If the array hasn't been passed, it has a default/fallback value as in example:
public function selectName($howMany = 1, $seed = ['john', 'bob', 'mark', 'cindy']){...
supporting questions:
a) Is storing filled array in default arguments a good idea?
b) Which would be better, a constant, array_merge
, if(empty...
?
Since the default values are shared with all of your objects, it is better to decalre them as static
.
Reducing the visibility to protected
is recommended
class YourClass {
protected static $_DEFAULT_SEED = array('john', 'bob', 'mark', 'cindy');
protected static $_DEFAULT_QUANTITY = 1;
public function selectName($howMany = NULL, $seed = NULL){
if (is_null($howMany)) {
$howMany = self::$_DEFAULT_QUANTITY;
}
if (is_null($seed)) {
$seed = self::$_DEFAULT_SEED;
}
//...
}
}
Better you pass an empty array as argument.
public function selectName($howMany = 1, $seed = array()){
$myarr=['john', 'bob', 'mark', 'cindy'];
if(count($seed)>0){
$myarr=$seed;
}
/* user $myarr now*/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With