Using function result as a default argument in PHP function

I'm writing a function which requires some units of date, like "hour", "minute" and "second" but I would like to make these option and the server's current time is used as the default.

In PHP's mktime(..) I notice that they use function calls to get the default argument value - but when I try this, it doesn't work:

PHP's appears to be like this: mktime([int $hour = date("H")[,int $minute= date("i")[,etc...

And I've tried to copy this into my function, exactly the same (just not as many arguments until I get it working): function myFunc([int $hour = date("H")[,int $minute= date("i")]]) {

Using this code, PHP tells me Parse error: syntax error, unexpected '[', expecting '&' or T_VARIABLE in ...

I've tried searching for this - but managed to find nothing on the topic. My question is, is this possible for me to do or am I going to have to specify null as the parameters and then check them inside the function like so:

function myFunc($hour=null,etc...) {
  if($hour==null){$hour=date("H");}
  //etc...
}

As for justification of why I want to know this other than using the solution I've provided to myself - I'm still learning PHP and want to learn the best practises.


A default function argument should be a compile time constant. Or in PHP's case the value should be known to the PHP interpreter before executing the script.

Therefore you cannot directly use function result as a default argument

Thus only way is the null default argument method you already know.

链接地址: http://www.djcxy.com/p/69700.html

上一篇: STRING,期待'('in

下一篇: 在PHP函数中使用函数结果作为默认参数