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"));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序