PHP Default Function Parameter Values, How to 'Pass Default Value' for 'Not Last' Parameters

PHP Default Function Parameter values, how to 'pass default value' for 'not last' parameters?

PHP doesn't support what you're trying to do. The usual solution to this problem is to pass an array of arguments:

function funcName($params = array())
{
$defaults = array( // the defaults will be overidden if set in $params
'value1' => '1',
'value2' => '2',
);

$params = array_merge($defaults, $params);

echo $params['value1'] . ', ' . $params['value2'];
}

Example Usage:

funcName(array('value1' => 'one'));                    // outputs: one, 2
funcName(array('value2' => 'two')); // outputs: 1, two
funcName(array('value1' => '1st', 'value2' => '2nd')); // outputs: 1st, 2nd
funcName(); // outputs: 1, 2

Using this, all arguments are optional. By passing an array of arguments, anything that is in the array will override the defaults. This is possible through the use of array_merge() which merges two arrays, overriding the first array with any duplicate elements in the second array.

Using Default Arguments in a Function

I would propose changing the function declaration as follows so you can do what you want:

function foo($blah, $x = null, $y = null) {
if (null === $x) {
$x = "some value";
}

if (null === $y) {
$y = "some other value";
}

code here!

}

This way, you can make a call like foo('blah', null, 'non-default y value'); and have it work as you want, where the second parameter $x still gets its default value.

With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.

As stated in other answers,

default parameters only work as the last arguments to the function.
If you want to declare the default values in the function definition,
there is no way to omit one parameter and override one following it.

If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.

Here is another example (this doesn't answer your question, but is hopefully informative:

public function __construct($params = null)
{
if ($params instanceof SOMETHING) {
// single parameter, of object type SOMETHING
} elseif (is_string($params)) {
// single argument given as string
} elseif (is_array($params)) {
// params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
} elseif (func_num_args() == 3) {
$args = func_get_args();

// 3 parameters passed
} elseif (func_num_args() == 5) {
$args = func_get_args();
// 5 parameters passed
} else {
throw new \InvalidArgumentException("Could not figure out parameters!");
}
}

php default arguments

You can use either:

example($argument1, '', 'test');

Or

example($argument1, NULL, 'test');

You can always check for NULL using instead of empty string:

if ($argument === NULL) {
//
}

I think it all depends on what happens inside the function with the args.

How to only pass an optional parameter to a PHP function by keeping all other mandatory/optional parameters(if any) equal to their default values?

Passing '' does not mean falling back to default argument value. It means just that — trying to pass an empty string.

You would need to reproduce defaults if you want to achieve this:

htmlspecialchars('&', ENT_COMPAT | ENT_HTML401, ini_get('default_charset'), FALSE);

Sending default parameter as null and use default value set in function

When you start the value parameters happens:


 function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

The above example will output:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

To fulfill what you want to check with conditions as follows:

function test($username, $is_active=1, $sent_email=1, $sent_sms=1) {

if($sent_email!=1)
$sent_email=1;
echo $sent_email; // It should print default ie 1

}

PHP : Passing 2nd argument on function but retain the default value of first argument

No you can't do that in this way. PHP excpects the values in the order you defined in the function.
However it is possible to pass data to your function as an array.

$res = check(array('a' => $defaulta, ..., 'c' => 5))

Where you have your default values in somethin like $defaulta/b/c. Or just write them hardcoded.

Hope this helps!

PHP Function Array Default Values?

You can only use scalar types for the default values of function arguments.

You can also read this in the manual: http://php.net/manual/en/functions.arguments.php#functions.arguments.default

And a quote from there:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

EDIT:

But if you still need this value as default value in the array you could do something like this:

Just use a placeholder which you can replace with str_replace() if the default array is used. This also has the advantage if you need the return value of the function in the default array multiple times you just need to use the same placeholder and both are going to be replaced.

public function create(
$data = [
"user-id" => "::PLACEHOLDER1::",
//^^^^^^^^^^^^^^^^ See here just use a placeholder
"level" => '1',
"ignore-limits" => '0',
]){
$data = str_replace("::PLACEHOLDER1::", Auth::id(), $data);
//^^^^^^^^^^^ If you didn't passed an argument and the default array with the placeholder is used it get's replaced
//$data = str_replace("::PLACEHOLDER2::", Auth::id(), $data); <- AS many placeholder as you need; Just make sure they are unique
//...
}

Another idea you could do is set a default array which you can check and then assign the real array like this:

public function create($data = []){
if(count($data) == 0) {
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
];
}
//...
}

PHP function with variable as default value for a parameter

No, this isn't possible, as stated on the Function arguments manual page:

The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.

Instead you could either simply pass in null as the default and update this within your function...

function actionOne($id=null) {
$id = isset($id) ? $id : $_GET['ID'];
....
}

...or (better still), simply provide $_GET['ID'] as the argument value when you don't have a specific ID to pass in. (i.e.: Handle this outside the function.)



Related Topics



Leave a reply



Submit