Search code examples
phpdatetimephp-5.3extendinheritance

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

Solution

  • 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();
            $parent_dt = parent::createFromFormat($format, $time);
    
            if (!$parent_dt) {
                return false;
            }
    
            $ext_dt->setTimestamp($parent_dt->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.