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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)