0

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?

0

1 Answer 1

2

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"));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well thats' mildly embarrassing, but explains why its' not working. Thanks for the prompt reply
We all have our weak moments. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.