How to skip optional arguments in a function call?

OK. I completely forgot how to skip arguments in PHP.

Let's say I have:

function getData($name, $limit = '50', $page = '1') { ... } 

How can I name this function so that the middle parameter accepts the default value (for example, "50")?

 getData('some name', '', '23'); 

Would that be right? I can't seem to get this to work.

+70
function php parameters optional-parameters default-value
Jun 30 '09 at 23:31
source share
17 answers

Your message is correct.

Unfortunately, if you need to use an optional parameter at the very end of the parameter list, you need to specify everything until the last parameter. Typically, if you want to mix and match, you give them the default value '' or null and do not use them inside the function if they are the default value.

+45
Jun 30 '09 at 23:35
source share

There is no way to β€œskip” an argument except to specify a default value, such as false or null .

Since PHP lacks syntactic sugar when it comes to this, you'll often see something like this:

 checkbox_field(array( 'name' => 'some name', .... )); 

Which, as eloquently stated in the comments, uses arrays to emulate named arguments.

This gives maximum flexibility, but in some cases may not be needed. At the very least, you can move what you think is not expected in most cases to the end of the argument list.

+35
Jun 30 '09 at 23:35
source share

No, it is impossible to skip arguments in this way. You can skip passing arguments only if they are at the end of the parameter list.

There was an official offer for this: https://wiki.php.net/rfc/skipparams , which was refused. The suggestion page is related to other SO questions on this topic.

+29
May 14 '15 at 15:22
source share

Nothing has changed regarding the ability to skip optional arguments, however, for the correct syntax and for the ability to specify NULL for the arguments that I want to skip, here's how I do it:

 define('DEFAULT_DATA_LIMIT', '50'); define('DEFAULT_DATA_PAGE', '1'); /** * getData * get a page of data * * Parameters: * name - (required) the name of data to obtain * limit - (optional) send NULL to get the default limit: 50 * page - (optional) send NULL to get the default page: 1 * Returns: * a page of data as an array */ function getData($name, $limit = NULL, $page = NULL) { $limit = ($limit==NULL) ? DEFAULT_DATA_LIMIT : $limit; $page = ($page==NULL) ? DEFAULT_DATA_PAGE : $page; ... } 

This can be called as follows: getData('some name',NULL,'23'); , and everyone calling the function in the future should not remember the default values ​​each time or the constant declared for them.

+5
May 18 '15 at 12:25
source share

The simple answer is No. But why skip when reinstalling the arguments achieves this?

You have " Misuse of function arguments by default " and will not work as you expect.

A note from the PHP documentation:

When using the default arguments, any default values ​​should be on the right side of any arguments other than the default; otherwise, everything will not work as expected.

Consider the following:

 function getData($name, $limit = '50', $page = '1') { return "Select * FROM books WHERE name = $name AND page = $page limit $limit"; } echo getData('some name', '', '23'); // won't work as expected 

The output will be:

 "Select * FROM books WHERE name = some name AND page = 23 limit" 

Proper use of function arguments by default should be like this:

 function getData($name, $page = '1', $limit = '50') { return "Select * FROM books WHERE name = $name AND page = $page limit $limit"; } echo getData('some name', '23'); // works as expected 

The output will be:

 "Select * FROM books WHERE name = some name AND page = 23 limit 50" 

When setting the default value to the right of non-default values, make sure that it will always reconfigure the default value for this variable if it is not defined / set. Here is the link for the link and where did these examples come from.

Edit: Configuring to null , as others may suggest, may work, and this is another alternative, but may not match what you want. It always sets the default value to null if it is not defined.

+3
May 20 '15 at 11:26
source share

You cannot skip arguments, but you can use array parameters, and you need to define only one parameter, which is an array of parameters.

 function myfunction($array_param) { echo $array_param['name']; echo $array_param['age']; ............. } 

And you can add as many parameters as you need, you do not need to define them. When you call a function, you enter your parameters as follows:

 myfunction(array("name" => "Bob","age" => "18", .........)); 
+2
May 15 '15 at 7:42
source share

As mentioned above, you cannot skip parameters. I wrote this answer to provide some addition that was too large to post a comment.

@Frank Nocke suggests calling a function with its default parameters, therefore, for example, having

 function a($b=0, $c=NULL, $d=''){ //... 

you should use

 $var = a(0, NULL, 'ddd'); 

which will function the same as omitting the first two parameters ( $b and $c ).

It is not clear which of these are the defaults ( 0 printed to indicate the default value, or is this important?).

There is also the danger that the default problem is related to an external (or built-in) function, when the default values ​​can be changed by the author of the function (or method). Therefore, if you do not change your call in the program, you may inadvertently change its behavior.

Some workaround may be to define some global constants, such as DEFAULT_A_B , which will be the "default value for parameter B of function parameter A" and "omit" as follows:

 $var = a(DEFAULT_A_B, DEFAULT_A_C, 'ddd'); 

For classes, this is simpler and more elegant if you define class constants because they are part of a global scope, for example.

 class MyObjectClass { const DEFAULT_A_B = 0; function a($b = self::DEFAULT_A_B){ // method body } } $obj = new MyObjectClass(); $var = $obj->a(MyObjectClass::DEFAULT_A_B); //etc. 

Please note that this constant is defined by default exactly once throughout the code (there is no value even in the method declaration), therefore, in case of unexpected changes, you will always supply the function / method with the correct default value.

The clarity of this solution is, of course, better than providing the original default values ​​(e.g. NULL , 0 , etc.) that tell the reader nothing.

(I agree that calling like $var = a(,,'ddd'); would be a better option)

+2
May 15 '15 at 10:56
source share

For any parameter missing (you should) go with the default parameter to be safe.

(Settling for null, where the default parameter is "or", or vice versa, will lead you to trouble ...)

+1
Jan 29 '13 at 10:07
source share

Well, like everyone else said that what you want would not be possible in PHP without adding any code lines to the functions.

But you can put this piece of code at the top of the function to get your functionality:

 foreach((new ReflectionFunction(debug_backtrace()[0]["function"]))->getParameters() as $param) { if(empty(${$param->getName()}) && $param->isOptional()) ${$param->getName()} = $param->getDefaultValue(); } 

So, basically with debug_backtrace() I get the name of the function in which this code is placed, to then create a new ReflectionFunction object and a loop, although all the arguments to the function.

In a loop, I just check to see if the function argument is empty() and the argument is "optional" (meaning it has a default value). If so, I simply assign a default value to the argument.

Demo

0
May 15 '15 at 20:04
source share

Set the limit to null

 function getData($name, $limit = null, $page = '1') { ... } 

and call this function

 getData('some name', null, '23'); 

if you want to set a limit that you can pass as an argument

 getData('some name', 50, '23'); 
0
May 16 '15 at 7:03
source share

As stated earlier , nothing has changed. Beware, however, too many parameters (especially optional ones) are a strong indicator of code smell.

Maybe your function is too much:

 // first build context $dataFetcher->setPage(1); // $dataFetcher->setPageSize(50); // not used here // then do the job $dataFetcher->getData('some name'); 

Some parameters can be grouped logically:

 $pagination = new Pagination(1 /*, 50*/); getData('some name', $pagination); // Java coders will probably be familiar with this form: getData('some name', new Pagination(1)); 

In the latter case, you can always enter a special object:

 $param = new GetDataParameter(); $param->setPage(1); // $param->setPageSize(50); // not used here getData($param); 

(this is just an illustrious version of a less formal parameter array method)

Sometimes the reason for entering the parameter is optional. In this example, does $page really mean it's optional? Does saving multiple characters really matter?

 // dubious // it is not obvious at first sight that a parameterless call to "getData()" // returns only one page of data function getData($page = 1); // this makes more sense function log($message, $timestamp = null /* current time by default */); 
0
May 19 '15 at 21:31
source share

This snippet:

     function getData ($ name, $ options) {
        $ default = array (
             'limit' => 50,
             'page' => 2,
         );
         $ args = array_merge ($ default, $ options);
         print_r ($ args);
     }

     getData ('foo', array ());
     getData ('foo', array ('limit' => 2));
     getData ('foo', array ('limit' => 10, 'page' => 10));

Answer:

      Array
     (
         [limit] => 50
         [page] => 2
     )
     Array
     (
         [limit] => 2
         [page] => 2
     )
     Array
     (
         [limit] => 10
         [page] => 10
     )

0
May 20 '15 at 1:07
source share

This is what I would do:

 <?php function getData($name, $limit = '', $page = '1') { $limit = (EMPTY($limit)) ? 50 : $limit; $output = "name=$name&limit=$limit&page=$page"; return $output; } echo getData('table'); /* output name=table&limit=50&page=1 */ echo getData('table',20); /* name=table&limit=20&page=1 */ echo getData('table','',5); /* output name=table&limit=50&page=5 */ function getData2($name, $limit = NULL, $page = '1') { $limit = (ISSET($limit)) ? $limit : 50; $output = "name=$name&limit=$limit&page=$page"; return $output; } echo getData2('table'); // /* output name=table&limit=50&page=1 */ echo getData2('table',20); /* output name=table&limit=20&page=1 */ echo getData2('table',NULL,3); /* output name=table&limit=50&page=3 */ ?> 

Hope this helps someone

0
Dec 18 '16 at 9:13
source share

Try it.

 function getData($name, $limit = NULL, $page = '1') { if (!$limit){ $limit = 50; } } getData('some name', '', '23'); 
-one
May 19 '15 at 8:10
source share

You cannot skip the middle parameter in a function call. But you can work with this:

 function_call('1', '2', '3'); // Pass with parameter. function_call('1', null, '3'); // Pass without parameter. 

Functions:

 function function_call($a, $b='50', $c){ if(isset($b)){ echo $b; } else{ echo '50'; } } 
-2
May 19 '15 at 19:06
source share

As @IbrahimLawal pointed out. It is best to set only null values. Just check to see if the null value in which you use your set defaults has passed.

 <?php define('DEFAULT_LIMIT', 50); define('DEFAULT_PAGE', 1); function getData($name, $limit = null, $page = null) { $limit = is_null($limit) ? DEFAULT_LIMIT : $limit; $page = is_null($page) ? DEFAULT_PAGE : $page; ... } ?> 

Hope this helps.

-2
May 20 '15 at 2:35
source share
 getData('some name'); 

just don't pass them and the default will be accepted

-5
May 19 '15 at 7:43
source share



All Articles