Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter - array default value | best practice

Tags:

php

arguments

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...?

like image 706
Unamata Sanatarai Avatar asked Jul 20 '15 10:07

Unamata Sanatarai


2 Answers

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;
        }
        //...
    }
}
like image 104
Halayem Anis Avatar answered Sep 29 '22 06:09

Halayem Anis


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*/
}
like image 38
Disha V. Avatar answered Sep 29 '22 05:09

Disha V.