Php new DateTime返回空的DateTime实例
跟踪bug的来源,我发现这段代码在开发和实时服务器中的行为不同:Php new DateTime返回空的DateTime实例,php,datetime,Php,Datetime,跟踪bug的来源,我发现这段代码在开发和实时服务器中的行为不同: <?php ini_set('log_errors', FALSE); ini_set('display_errors', TRUE); error_reporting(E_ALL ^ E_STRICT); var_dump(date_default_timezone_set('Europe/Madrid')); try{ $dt = new DateTime('2010-12-01'); var_du
<?php
ini_set('log_errors', FALSE);
ini_set('display_errors', TRUE);
error_reporting(E_ALL ^ E_STRICT);
var_dump(date_default_timezone_set('Europe/Madrid'));
try{
$dt = new DateTime('2010-12-01');
var_dump($dt);
}catch(Exception $e){
var_dump($e);
}
在live server(PHP/5.2.14)中,我得到一个空白对象:
bool(true)
object(DateTime)#1 (0) {
}
我已经放弃了通常的怀疑(缺少默认时区、不可解析的日期字符串…)。此代码在两台服务器中具有相同的输出:
<?php
ini_set('log_errors', FALSE);
ini_set('display_errors', TRUE);
error_reporting(E_ALL ^ E_STRICT);
var_dump(date_default_timezone_set('Europe/Madrid'));
$ts = strtotime('2010-12-01');
var_dump($ts, date('r', $ts));
我遗漏了一些非常明显的东西吗?尝试使用这个在5.1/5.2 php上使用的变通方法
<?php
if (!class_exists('DateTime')) {
class DateTime {
public $date;
public function __construct($date) {
$this->date = strtotime($date);
}
public function setTimeZone($timezone) {
return;
}
private function __getDate() {
return date(DATE_ATOM, $this->date);
}
public function modify($multiplier) {
$this->date = strtotime($this->__getDate() . ' ' . $multiplier);
}
public function format($format) {
return date($format, $this->date);
}
}
}
?>
尝试使用在5.1/5.2 php上使用的此解决方案
<?php
if (!class_exists('DateTime')) {
class DateTime {
public $date;
public function __construct($date) {
$this->date = strtotime($date);
}
public function setTimeZone($timezone) {
return;
}
private function __getDate() {
return date(DATE_ATOM, $this->date);
}
public function modify($multiplier) {
$this->date = strtotime($this->__getDate() . ' ' . $multiplier);
}
public function format($format) {
return date($format, $this->date);
}
}
}
?>
对于PHP5.2,您必须使用
$date = new DateTime('2010-12-01');
echo $date->format('Y-m-d');
显然你不能在DateTime的5.2版本上进行var_转储。可能与他们如何在5.2中使用PHP5.2设置类有关
$date = new DateTime('2010-12-01');
echo $date->format('Y-m-d');
显然你不能在DateTime的5.2版本上进行var_转储。可能与他们如何在5.2中设置类有关。你是对的,问题在于
var_dump()
本身。如果我做了echo$dt->format('r')
这个值就可以了。我是一个初学者,但我真的不同意这个答案。我有newdatetime()代码>不使用PHP5.2在生产服务器中创建当前日期对象,而使用PHP5.4在localhost中创建它。我认为显示变量与创建变量没有关系。@whitelettersandblankspaces没有人说这与创建和显示有关系,我只是说他不能var_转储DateTime
对象,也不能获得与php版本大于5.2时相同的对象转储。你是对的,问题在于var_转储()
本身。如果我这样做echo$dt->format('r')
值就很好了。它将再次研究基本问题。我是初学者,但我真的不同意这个答案。我有new DateTime();
不使用PHP5.2在生产服务器中创建当前日期对象,而使用PHP5.4在localhost中创建它。我认为显示变量与创建它没有关系。@WhiteLettersandBlankspace没有人说与创建和显示有关系,我只是说他不能将日期时间
对象变为变量并获取在php版本大于5.2时,他会得到相同的对象转储。DateTime类实际上存在于php/5.2中。它只是缺少php/5.3中的一些修复、改进和增强;-)DateTime类实际上存在于php/5.2中。它只是缺少了PHP/5.3中的一些修复、改进和增强功能;-)