问题描述
我正在尝试如下扩展DateTime:
class testdate extends DateTime {
public $sqldate;
public function __construct($time)
{
parent::__construct($time);
//?? parent::modify();
$this->sqldate = $this->format ("Y-m-d");
}
}
echo "<pre>";
$td = new testdate("2020-08-23");
echo " Today's Date: ".$td->format ("m/d/Y").br;
echo " Today's sql Date: ".$td->sqldate.br.br;
$td->modify ("+24 hour");
echo " Tomorrow;s Date: ".$td->format ("m/d/Y").br; // 1 day added correctly
echo " Tomorrow Formatted: ".$td->format ("Y-m-d").br;
echo " Tomorrow sql Date: ".$td->sqldate.br.br; //not updated
print_r ($td);
如您在print_r语句中所见,日期已更新,但sqldate未更新。
我该怎么做才能确保扩展类的属性已更新?
解决方法
正如已经提到的,实际的问题是,您仅设置了在构造函数内部定义的sqldate
属性,因此在实例化对象时只设置一次。您无处实现对该属性的更新。
有可能进一步扩展派生类,以使sqldate
属性在每次修改时都得到更新,但这很麻烦且容易出错。原因是该属性保留了冗余信息,然后需要对其进行同步。
在这种情况下,使用格式化方法而不是同步功能更为优雅:
<?php
define("br","\n");
class testdate extends DateTime {
public function getSqlDate() {
return $this->format("Y.m.d");
}
}
$td = new testdate("2020-08-23");
echo " Today's Date: ".$td->format ("m/d/Y").br;
echo " Today's SQL Date: ".$td->getSqlDate().br.br;
$td->modify ("+24 hour");
echo " Tomorrow's Date: ".$td->format ("m/d/Y").br;
echo " Tomorrow Formatted: ".$td->format ("Y-m-d").br;
echo " Tomorrow Sql Date: ".$td->getSqlDate().br.br;
明显的输出是:
Today's Date: 08/23/2020
Today's SQL Date: 2020.08.23
Tomorrow's Date: 08/24/2020
Tomorrow Formatted: 2020-08-24
Tomorrow Sql Date: 2020.08.24