Reputation: 1449
I currently have this code.
function outputCalendarByDateRange($client, $startDate="2011-06-22",
$endDate='2011-06-26')
I want $startDate and $endDate to reflect today's date and the date three days from now with it automatically updating. I've tried using
$startDate=date("Y-m-D")
$endDate=strtotime(date("Y-m-d", strtotime($todayDate)) . " +3 days");
and
$date1=date("Y-m-D")
$date2=strtotime(date("Y-m-d", strtotime($todayDate)) . " +3 days");
function outputCalendarByDateRange($client, $startDate=$date1,
$endDate=$date2)
none of these work. How do I make it work?
Thanks!
Upvotes: 1
Views: 813
Reputation: 13812
I'm gonna take a guess and say that you're trying to set $date1 equal to the variable in the function. That's not necessary, just list them in order. function outputCalendarByDateRange($client, $date1, $date2)
Upvotes: -1
Reputation: 732
You can't pass variables as default values. See below for a possible solution to what you're trying to achieve:
<?php
error_reporting(E_ALL);
$defaultStartDate = date("Y-m-d");
$defaultEndDate = date("Y-m-d", strtotime($defaultStartDate . " + 3 days"));
function outputCalendarByDateRange($client, $startDate="", $endDate="") {
global $defaultStartDate, $defaultEndDate;
if ($startDate === "") {
$startDate = $defaultStartDate;
}
if ($endDate === "") {
$endDate = $defaultEndDate;
}
echo "Client: " . $client . "<br />";
echo "Start Date: " . $startDate . "<br />";
echo "End Date: " . $endDate . "<br />";
}
outputCalendarByDateRange("Test Client");
echo "<br />";
outputCalendarByDateRange("Test Client #2", date("Y-m-d", strtotime("2011-06-01")), date("Y-m-d", strtotime("2011-07-01")));
?>
Output:
Client: Test Client
Start Date: 2011-06-23
End Date: 2011-06-26
Client: Test Client #2
Start Date: 2011-06-01
End Date: 2011-07-01
Upvotes: 1
Reputation: 145482
You cannot have expressions in the function declaration. But constants could be a workaround for what you want to do.
define("FUNC_CAL_DATE1", date("Y-m-D"));
define("FUNC_CAL_DATE2", strtotime(date("Y-m-d",strtotime($to...
function outputCalendarByDateRange($client,
$startDate=FUNC_CAL_DATE1, $endDate=FUNC_CAL_DATE2) {
They are actually expressions too, but are specially handled in this context and work where the =$date1
wouldn't.
Upvotes: 3
Reputation: 522081
You can't have variable default argument values, you'll have to solve this in code:
function outputCalendarByDateRange($client, $startDate = null, $endDate = null) {
$startDate = $startDate ? $startDate : date('Y-m-d');
$endDate = $endDate ? $endDate : date('Y-m-d', strtotime('+3 days'));
...
}
Calling this function without the second and third argument will use the current date/current date +3, calling it with arguments you can specify your own values.
Upvotes: 0
Reputation: 179046
you can't use a statement in a function declaration, but you can set the value to null and check it at runtime:
function foo( $bar = null )
{
if (is_null($bar))
{
$bar = 'baz';
}
...code...
}
Upvotes: 4