13

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?

1

2 Answers 2

15

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

i think you mean arg2 = (arg2==null) ? time() : arg2;
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.