Search code examples
phpfunctionlanguage-designdefault-value

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?


Solution

  • 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);
    }