Using an array as a default parameter in a PHP function
(It might not be a complete answer, but it covers some useful cases.)
If you want to get one or more options using an array as an argument in a function (or a method), setting a default set of options might not help. Instead, you can use array_replace()
.
For example, let's consider a sample $options
argument which gets an array with two keys, count
and title
. Setting a default value for that argument leads overriding it when using the function with any custom $option
value passed. In the example, if we set $options
to have only one count
key, then the title
key will be removed. One of the right solutions is the following:
function someCoolFunc($options = []) {
$options = array_replace([
"count" => 144,
"title" => "test"
], $options);
// ...
}
In the example above, you will be ensured that count
and title
indexes are present, even if the user supplies an empty array (keep in mind, the order of the arguments in array_replace()
function is important).
Note: In the explained case, using a class (or interface) is also an option, but one reason to choose arrays over it might be simplicity (or even performance).
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');
You can't pass $arr
into the function definition, you'll have to do:
function sample($var1, $var2, $var3 = array('test')){
echo $var1.$var2;
echo print_r($var3);
}
sample('a','b'); // output: abArray ( [0] => test ) 1
or, if you want to be really dirty (I wouldn't recommend it..):
$arr = array('test');
function sample($var1, $var2, $var3 = null){
if($var3 == null){
global $arr;
$var3 = $arr;
}
echo $var1.$var2;
echo print_r($var3);
}
sample('a','b');