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
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');
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