dsfs587465 2012-10-21 00:21
浏览 26
已采纳

无法在PHP中的函数参数中指定动态变量

Doing a bit of coding, and wanted to set a default value of today's date for an argument in a function that I have. However, having a bit of problems having it work and have it still be dynamic. This is current setup, where I have static values assigned to certain function arguments.

private function search($text, $startDate = "2012-10-19", $endDate = "2012-10-20") { //code goes here }

Not what I want, but it's what works, and the IDE doesnt' complain.

This is what I've tried, with the corresponding complaints from the interpreter

private function search($text, $startDate = $this->getCurrentDate(), $endDate = "2012-10-20") { //code goes here }

returns "syntax error, unexpected $this", where getCurrentDate refers to a private function that only returns a string. Same co-occurrence happens when I call a variable declared in class scope (minus the brackets at the end of getCurrentDate of course). Utilizing static brings up "Undefined class constant 'self::getCurrentDate ' ", regardless of whether I call it as a function or a class scope variable which is odd since I've defined it as such.

    private static function getDate() {
    return "foo";
}

and

private static $getTodaysDate = date("M-d-Y", mktime(0, 0, 0, date("M"), date("d"), date("Y")));

in my two different attempts. Of course this

private function search($text, $startDate = date("M-d-Y", mktime(0, 0, 0, date("M"), date("d"), date("Y"))), $endDate = "2012-10-20") { //code goes here }

doesn't work at all.

So I'm sure it's just some obvious thing I'm missing, but I cannot see why PHP is not allowing me to do this without declaring a static string, or if I'm running against a limitation of the language. Anyone have any ideas as to what's the cause?

  • 写回答

1条回答 默认 最新

  • dongnai5905 2012-10-21 00:24
    关注

    Default values for function parameters can not be dynamic!
    From the PHP Manual on default values for function parameters:

    The default value must be a constant expression, not (for example) a variable, a class member or a function call.

    What you could do is set the default parameter to null and then in your function check if the parameter is null and if so overwrite it with the current date.

    private function search($text, $startDate = null, $endDate = "2012-10-20") {
        if ($startDate === null) $startDate = date("M-d-Y", mktime(0, 0, 0, date("M"), date("d"), date("Y"));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况