开发者

make date_create() work with DateTime child class

One of the annoying things about php's DateTime class is that it doesn't have a __toString() method, meaning that it throws an error every time you try to use it in a string context. So I extended it:

class ZDateTime extends DateTime {

    private $zformat='Y-m-d H:i:s';

    function __toString() {
        return $this->format($this->zformat);
    }

    function set_format($format){
        $this->zformat=$format; //leaving out format validation for brevity
    }
}

But now I've lost all the nice procedural functions that DateTime has like date_create() and many of the other functions listed here.

I know that the procedural functions are just aliases for DateTime class methods. But they are often easier to use and are liberally sprinkled throughout my code. Fishing them out will be a seve开发者_StackOverflow中文版re pain. So, any idea how I can make date_create() return a ZDateTime object?


The easiest way is probably just to create a zdate_create function and do a mass search & replace.

It can be done, but the only way you can do that in vanilla PHP (i.e.: without runkit and such) is:

ZDateTime.php

namespace MyDateTime;

class ZDateTime extends \DateTime {
    // do your stuff
}

function date_create($time = 'now', \DateTimeZone $timezone = null) {
    if (isset($timezone)) {
        return new ZDateTime($time, $timezone);
    } else {
        return new ZDateTime($time);
    }
}

Some_Script.php

namespace MyDateTime;
include 'ZDateTime.php';

$foo = date_create();
var_dump($foo); // ZDateTime object


So, any idea how I can make date_create() return a ZDateTime object?

You can't do that. With very few exceptions (PDO), the built-in classes and functions that return new instances are unable to return subclasses instead.

Consider adding a new static method to your ZDateTime class that performs the same thing: Create the object, but return false instead of throwing an exception when the passed string is unparsable. You'll just need to catch the exception inside the function.


date_create() is an alias of a DateTime constructor. So just create a new instance of ZDateTime.

You could do this in your class if you find yourself with a DateTime object:

public static function fromDateTime(DateTime $foo)
{
  return new static($foo->format('Y-m-d H:i:s e')); 
}

$foo = ZDateTime::fromDateTime($dt);

Then you could extend some of the static methods like:

public static function createFromFormat($f, $t, $tz)
{
  return static::fromDateTime(parent::createFromFormat($f, $t, $tz));
}

$dt = ZDateTime::createFromFormat(...);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜