Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make DateTime::createFromFormat() return child class instead of parent

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;
    }
}
like image 884
noisebleed Avatar asked Mar 27 '11 15:03

noisebleed


1 Answers

I think your solution is fine. An alternative way (just refactored a bit) is this:

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));
}

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.

like image 168
Matthew Avatar answered Oct 12 '22 22:10

Matthew