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?
Default values for function parameters can not be dynamic!
From the PHP Manual on default values for function parameters:
What you could do is set the default parameter to
nulland then in your function check if the parameter isnulland if so overwrite it with the current date.