Reputation: 5264
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?
Upvotes: 13
Views: 6830
Reputation: 574
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.
Upvotes: 4
Reputation: 6265
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);
}
Upvotes: 15