Viewed   71 times

Let's say I've got a PHP function foo:

function foo($firstName = 'john', $lastName = 'doe') {
    echo $firstName . " " . $lastName;
}
// foo(); --> john doe

Is there any way to specify only the second optional parameter?

Example:

foo($lastName='smith'); // output: john smith

 Answers

2

PHP does not support named parameters for functions per se. However, there are some ways to get around this:

  1. Use an array as the only argument for the function. Then you can pull values from the array. This allows for using named arguments in the array.
  2. If you want to allow optional number of arguments depending on context, then you can use func_num_args and func_get_args rather than specifying the valid parameters in the function definition. Then based on number of arguments, string lengths, etc you can determine what to do.
  3. Pass a null value to any argument you don't want to specify. Not really getting around it, but it works.
  4. If you're working in an object context, then you can use the magic method __call() to handle these types of requests so that you can route to private methods based on what arguments have been passed.
Tuesday, November 1, 2022
5

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

Monday, October 10, 2022
4

Change your sub and add ByVal

Public Sub CalculateMe(Optional ByVal strA As String, Optional ByVal strB As String)
Saturday, December 3, 2022
 
htx9
 
3

There's no other way to do it in a ServletFilter other than trying to parse the URI yourself, but you can access the path parameters if you decide to use a JAX-RS request filter:

@Provider
public class PathParamterFilter implements ContainerRequestFilter {

    @Override
     public void filter(ContainerRequestContext request) throws IOException {
        MultivaluedMap<String, String> pathParameters = request.getUriInfo().getPathParameters();
        pathParameters.get("status");
        ....
    }
}
Thursday, November 3, 2022
 
2

SpreadsheetGear provides no option to specify the encoding of a CSV file, or option to specify what delimiter is used for a given text-based data file. If you have a CSV encoded with UTF, you would need to build your own routine that reads and handles this file accordingly, then manually insert that data into your worksheet cell-by-cell.

Tuesday, December 20, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :