我正在扩展 DateTime
添加一些有用的方法和常量。
使用时 new
创建一个新对象一切都很好但是在使用静态方法时 createFromFormat
它总是返回原始 DateTime
对象,当然没有任何子方法可用。
我使用以下代码来规避这个问题。这是最好的方法吗?
namespace NoiseLabs\DateTime;
class DateTime extends \DateTime
{
static public function createFromFormat($format, $time)
{
$ext_dt = new self();
$ext_dt->setTimestamp(parent::createFromFormat($format, time)->getTimestamp());
return $ext_dt;
}
}
这是要走的路。但是,因为你想要做的是渲染DateTime类可扩展,我建议你使用 static
代替 self
:
namespace NoiseLabs\DateTime;
class DateTime extends \DateTime
{
static public function createFromFormat($format, $time)
{
$ext_dt = new static();
$parent_dt = parent::createFromFormat($format, $time);
if (!$parent_dt) {
return false;
}
$ext_dt->setTimestamp($parent_dt->getTimestamp());
return $ext_dt;
}
}
没有必要,如果你不打算扩展课程,但如果有人这样做,它将阻止他再次做同样的解决方法。
我认为您的解决方案很好。另一种方法(只是重构一下)是这样的:
public static function fromDateTime(DateTime $foo)
{
return new static($foo->format('Y-m-d H:i:s e'));
}
public static function createFromFormat($f, $t, $tz)
{
return static::fromDateTime(parent::createFromFormat($f, $t, $tz));
}
我不确定实施该方法的最佳方法是什么 fromDateTime
是。你甚至可以拿走你所拥有的东西并把它放在那里。只要确保不要丢失时区。
请注意,您甚至可以实施 __callStatic
并使用一点反思使其成为未来的证据。
class DateTimeEx extends DateTime
{
static public function createFromFormat($format, $time, $object = null)
{
return new static(DateTime::createFromFormat($format, $time, $object)->format(DateTime::ATOM));
}
}