1

I am trying to create a Calendar class that takes a new DateTime in its constructor or left blank to use the current time.

<?php
class Calendar
{
    public $dateTime = null;
    public function __construct($dateTime = new DateTime())
    {
        $this->dateTime = $dateTime;
        echo $this->dateTime->format('m-d-Y') . "\n";
    }
}
date_default_timezone_set('UTC');
$cal = new Calendar();
?>

but I keep getting this:

Parse error: parse error in /Users/nfior2/www/projects/companies/cortlandt/activities/cal.php on line 5

If I change line 5

public function __construct($dateTime = new DateTime())

to use int

public function __construct($dateTime=10)

and adjust the function __construct() body a bit without using DateTime::format... it works as I would expect.

Can anyone tell me what is going on here or how I can get to the bottom of this?

nf071590
  • 1,170
  • 1
  • 13
  • 17

1 Answers1

1

You can try this code :

<?php
class Calendar
{
    public $dateTime = null;
    public function __construct($dateTime = null)
    {
        $this->dateTime = (isset($dateTime)? $dateTime : new DateTime());
        echo $this->dateTime->format('m-d-Y') . "\n";
    }
}
date_default_timezone_set('UTC');
$test = new DateTime('2000-01-01');

$cal1 = new Calendar($test);
$cal2 = new Calendar();
?>
  • Cool, this works awesome. Can you help explain why my code was not working? I was also curious why I was having trouble setting `public $dateTime = new DateTime();` in my property declarations when I was messing around with this class. I was getting the same error described in the question. – nf071590 Sep 04 '14 at 15:20
  • I have corrected the name of the variable in `isset($dateTime)` and added another for testing purposes –  Sep 04 '14 at 15:34