Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array as a default parameter in a PHP function

Tags:

arrays

php

Is it possible to use an array as a default parameter in a PHP function?

I would like to do the following:

$arr = array(1,2,3,4);

function sample($var1, $var2, $var3 = $arr){
    echo $var1.$var2;
    print_r($var3);
}

sample('a','b');
// Should still work without the third parameter and default to $arr
like image 458
Jasdeep Khalsa Avatar asked Jan 22 '13 10:01

Jasdeep Khalsa


1 Answers

No, this is not possible, the right hand expression of the default value must be a constant or array literal, i.e.

function sample($var1, $var2, $var3 = array(1, 2, 3, 4))
{
}

If you want this behaviour, you could use a closure:

$arr = array(1, 2, 3, 4);

$sample = function ($var1, $var2, array $var3 = null) use ($arr) {
    if (is_null($var3)) {
        $var3 = $arr;
    }

    // your code
}

$sample('a', 'b');

You could also express it with a class:

class Foo
{
    private static $arr = array(1, 2, 3, 4);

    public static function bar($var1, $var2, array $var3 = null)
    {
        if (is_null($var3)) {
            $var3 = self::$arr;
        }

        // your code here
    }
}

Foo::bar('a', 'b');
like image 60
Ja͢ck Avatar answered Nov 09 '22 00:11

Ja͢ck