从父级的静态方法返回子类


Return child class from parent's static method

我刚刚了解了 PHP 5.4 的这个奇特的新功能。 JsonSerializable! 这非常适合我的应用程序。

我的应用程序使用 DateTime 对象,当我json_encode它们时,我得到以下内容(通过运行 json_encode([new DateTime])):

[{"date":"2013-09-11 15:39:22","timezone_type":3,"timezone":"UTC"}]

根据timezone_type的不同,timezone值可能会有所不同。 我还没有找到在 JavaScript 中解析这个对象的好方法。

因此,我决定创建自己的 DateTime 类,并按照我想要的方式将其序列化为 JSON。

class SerialDateTime extends DateTime implements JsonSerializable{
    public function jsonSerialize(){
        return ['timestamp' => $this->getTimestamp()];
    }
}

当我现在运行json_encode([new SerialDateTime])时,我得到这个:

[{"timestamp":1378914190}]

这在JavaScript中更容易解析。

所以,我认为这是一个很好的解决方案,但我发现了一个问题。 静态方法! SerialDateTime::createFromFormat返回一个DateTime对象!

如果我这样做:json_encode([SerialDateTime::createFromFormat('m/d/Y', '10/31/2011')]),我会得到:

[{"date":"2011-10-31 15:46:07","timezone_type":3,"timezone":"UTC"}]

为什么会这样? SerialDateTime::createFromFormat为什么不还给我一个SerialDateTime对象?!

如何解决此问题,还是需要覆盖SerialDateTimeDateTime的所有静态方法? 如果我这样做,我什至如何从createFromFormat方法制作新的SerialDateTime? 如何将DateTime对象"投射"到SerialDateTime

我想到了一个解决方法,但必须有更好的方法:

public static function createFromFormat($f, $t, $tz=NULL){
    $dateTime = call_user_func(
        array('SerialDateTime', 'parent::createFromFormat'),
        $f, $t, $tz
    );
    $ret = new self();
    return $ret->setTimestamp($dateTime->getTimestamp());
}

我可以使用__callStaticreturn call_user_func_array(array(__CLASS__ , 'parent::'.__FUNCTION__), func_get_args());什么的吗?

太糟糕了,我无法神奇地将DateTime转换为使用后期静态绑定。

就像你已经说过的,并尝试过,覆盖静态方法。方法createFromFormat默认返回DateTime对象,因此您只需要修复返回部分,以便它将SerialDateTime而不是DateTime返回您的对象。

class SerialDateTime extends DateTime implements JsonSerializable {
    public function jsonSerialize()
    {
        return ['timestamp' => $this->getTimestamp()];
    }
    public static function createFromFormat($format, $time, $timezone = null)
    {
        if ($timezone) {
            $dt = parent::createFromFormat($format, $time, $timezone);
        } else {
            $dt = parent::createFromFormat($format, $time);
        }
        return new self($dt->format(self::W3C));
    }
}
echo json_encode(new SerialDateTime);
echo json_encode(SerialDateTime::createFromFormat('Y', '2013'));

不管你如何调用静态方法createFromFormat,它总是会返回DateTime对象;所以你所有自动重写静态方法的想法都会失败,因为你需要使用新的逻辑修改方法(返回其他对象的实例),而这不能用自动调用方法魔术或其他东西来完成。

如果在 DateTime::createFromFormat 方法中实现后期静态绑定会很棒,例如:

public static function createFromFormat($format, $time, $timezone = null)
{
    // logic of converting $time from format $format to some default format 
    return new static($newTime);
}

。但这不是;(源代码

所以,我将在这里发布我的答案。

在我看来,覆盖静态函数createFromFormat是处理问题的最佳方法。

因为:

  • 您的代码将保持干净(没有任何不必要的call_user_func
  • 重写父类方法并将类逻辑保留在类中是正确的。
  • 您的类SerialDateTime将可进一步重用。(如果只想导入类代码)

但是,没有必要重写所有方法(除非您实现接口)。仅覆盖您需要的内容。