dongmeixi5311 2011-09-15 17:35
浏览 36
已采纳

使用函数结果作为PHP函数中的默认参数

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.

  • 写回答

1条回答 默认 最新

  • doudi8829 2011-09-15 17:45
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题