Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP default argument function call

In php we can pass default arguments to a function like so

function func_name(arg1,arg2=4,etc...) {

but to my understanding we can not pass a function call so this is illegal:

function func2_name(arg1,arg2=time(),etc...) {

so when I want to do a function value (imagine like the time function the value cant be known ahead of runtime) I have to do a kind of messy work around like so:

function func3_name(arg1,arg2=null,etc...) {
    if(arg2==null) arg2 = time();

I was wondering if anyone knows a better way, a cleaner way to pass in function call values as default arguments in php? Thanks.

Also is there any fundamental reason in php language design that it doesn't allow function calls as default arguments (like does it do something special in the preprocessing?) or could this become a feature in future versions?

like image 756
hackartist Avatar asked Jun 11 '12 19:06

hackartist


People also ask

What is default argument in function in PHP?

PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.

What is function call argument?

Calling the function involves specifying the function name, followed by the function call operator and any data values the function expects to receive. These values are the arguments for the parameters defined for the function. This process is called passing arguments to the function.

What is default argument function?

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).

How will you passing an argument to a function in PHP?

PHP Function ArgumentsArguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.


2 Answers

Well, the short answer is that there is no better way to do it, to my knowledge. You can, however, make it look somewhat neater by using ternary operators.

function func3_name(arg1,arg2=null,etc...) {
  arg2 = (arg2==null ? time() : arg2);
}
like image 98
Connor Peet Avatar answered Sep 30 '22 20:09

Connor Peet


Connor is 100% correct; however, as of PHP 7, you can now use the null coalesce operator.

i.e.

$arg2 = $arg2 ?? time();

Just a shorter, arguably cleaner, way to write it.

like image 23
Henry Avatar answered Sep 30 '22 19:09

Henry