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?
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.
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.
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).
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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With