使 DateTime::createFromFormat() 返回子类而不是父类
我正在扩展 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;
}
}
I'm extending DateTime
do add some useful methods and constants.
When using new
to create a new object everything is fine but when using the static method createFromFormat
it always returns the original DateTime
object and of course none of the child methods are available.
I am using the following code to circumvent this issue. Is this the best approach?
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是要走的路。但是,由于您似乎想要做的是使 DateTime 类可扩展,因此我建议您使用
static
而不是self
:如果您不这样做,则没有必要计划延长课程时间,但如果有人这样做,这将阻止他再次采取相同的解决方法。
This is the way to go. However, since what seems you want to do is to render the DateTime class extensible, I'd suggest you use
static
instead ofself
:It's not necessary if you don't plan on extending the class, but if someone ever does, it will prevent him from having to do the same workaround again.
我认为你的解决方案很好。另一种方法(只是重构了一点)是这样的:
我不确定实现 fromDateTime 的最佳方法是什么。你甚至可以把你拥有的东西放在那里。只要确保不要丢失时区即可。
请注意,您甚至可以实现 __callStatic 并使用一些反射来使其面向未来。
I think your solution is fine. An alternative way (just refactored a bit) is this:
I'm not sure what the best way to implement the
fromDateTime
is. You could even take what you've got and put it in there. Just make sure not to lose the timezone.Note that you could even implement
__callStatic
and use a bit of reflection to make it future proof.以前的解决方案忽略了时区和微秒,所以我的一点改进就在这里。
我更喜欢变体 1,但就性能而言,变体 2 在旧 PHP 上可能会快一点。
Previous solutions neglect time zones and microseconds, so my little improve is here.
I prefer variant 1, but in terms of performance 2 can be little faster on old PHPs.