Make DateTime :: createFromFormat()返回子类而不是父类 [英] Make DateTime::createFromFormat() return child class instead of parent
问题描述
我正在扩展 DateTime
添加一些有用的方法和常量。
I'm extending DateTime
do add some useful methods and constants.
当使用新建
创建新对象时,一切都很好,但使用静态方法 createFromFormat
它总是返回原始的 DateTime
对象,当然没有一个子方法可用。
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;
}
}
推荐答案
是要走的路然而,由于你想要做的是渲染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 of self
:
namespace NoiseLabs\DateTime;
class DateTime extends \DateTime
{
static public function createFromFormat($format, $time)
{
$ext_dt = new static();
$ext_dt->setTimestamp(parent::createFromFormat($format, $time)->getTimestamp());
return $ext_dt;
}
}
如果您不打算延长该课程,但如果有人曾经做过,这将阻止他再次做同样的解决方法。
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.
这篇关于Make DateTime :: createFromFormat()返回子类而不是父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!