2014-09-04 101 views
1

我正在尝试创建一个 Calendar class,它的构造函数中需要一个new DateTime,或者留空以使用当前时间。带日期时间的PHP日历类

<?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(); 
?> 

,但我不断收到这样的:如果我解析错误/Users/nfior2/www/projects/companies/cortlandt/activities/cal.php第5行

解析错误改变线5

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

到使用int

public function __construct($dateTime=10) 

并调整function __construct()正文有点没有使用DateTime::format ...它工作正如我所料。

任何人都可以告诉我这里发生了什么,或者我可以怎么做到底?

回答

1

你可以试试这个代码:

<?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(); 
?> 
+0

酷,这工作真棒。你能解释为什么我的代码不工作吗?我也很好奇,为什么我在我的属性声明中设置'public $ dateTime = new DateTime();'时遇到了麻烦。我遇到了问题中描述的相同错误。 – nf071590 2014-09-04 15:20:28

+0

http://stackoverflow.com/questions/2202995/declare-property-as-object – nf071590 2014-09-04 15:25:55

+0

我更正了'isset($ dateTime)'中的变量名称,并添加了另一个用于测试目的 – 2014-09-04 15:34:34