2011-03-27 74 views
10

我在擴展DateTime確實添加了一些有用的方法和常量。使DateTime :: createFromFormat()返回子類而不是父類

當使用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; 
    } 
} 
+0

這就是我會做。 – lonesomeday 2011-03-27 15:43:37

+0

好的。感謝您閱讀本文,@lonesomeday。 – noisebleed 2011-03-27 17:25:18

回答

10

這是要走的路。然而,因爲什麼,似乎你想要做的是使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; 
    } 
} 

這不是必要的,如果你不擴展類的計劃,但如果有人這樣做,這將阻止他再次做同樣的解決方法。

+0

的確,這是一個很好的做法,感謝將「靜態」帶入遊戲。我希望模仿'createFromFormat'和替換'self'用'static'但因爲'DateTime'是一個C實現我猜有什麼我可以做,對不對? – noisebleed 2011-03-27 17:29:48

0

我認爲您的解決方案是好的。另一種方法(只是重構了一下)是這樣的:

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和使用位反射,使其面向未來。

0
class DateTimeEx extends DateTime 
{ 
    static public function createFromFormat($format, $time, $object = null) 
    { 
     return new static(DateTime::createFromFormat($format, $time, $object)->format(DateTime::ATOM)); 
    } 
}