php - 我应该在我的 php 项目中使用 `DateTimeInterface` 吗?

标签 php datetime interface

最近,我发现有一个DateTimeInterface .当我使用 \DateTime\DateTimeImmutable 时,我认为输入提示会很好。

然而在 php.net 上的变更日志上它说从 5.5.8 开始:

Trying to implement DateTimeInterface raises a fatal error now. Formerly implementing the interface didn't raise an error, but the behavior was erroneous.

上面写着我永远无法实现我自己的 CustomDateTime 类来实现 DateTimeInterface,这看起来很奇怪。

我应该在用户空间代码中使用 DateTimeInterface 吗?

我的直觉告诉我不要这样做。然而,对对象进行类型提示也是不对的,即

@var \DateTime|\DateTimeImmutable|\MyCustomDateTime

最佳答案

当您期望任何一种 native DateTime 变体时,您可以使用 DateTimeInterface 类型提示,例如\DateTime\DateTimeImmutable

但正如文档所说

It is not possible to implement this interface with userland classes.

因此,如果您计划使用您自己的实现来实现 \DateTimeInterface,这将不起作用,例如

class MyDateTime implements \DateTimeInterface {} // will raise an error

但是,您可以创建自己的界面并改编 native DateTime 类。

interface MyDateTime { /* some methods */ }

class NativeDateTime implements MyDateTime 
{
    private $dateTime;

    public function __construct($args = 'now') {
        $this->dateTime = new \DateTimeImmutable($args);
    }

   /* some methods */
}

或者您可以扩展 native DateTime 变体,然后显然会实现 DateTimeInterface,例如

class MyDateTime extends \DateTimeImmutable 
{
    /* your modifications */
}

var_dump(new MyDateTime instanceof \DateTimeInterface); // true

详细说明为什么您不能实现自己的实现 \DateTimeInterface 的类:

tl;dr core functions that accept DateTime and DateTimeImmutable (DateTimeInterface basically) operate directly on timelib structures hence they will break if you pass them a user-defined class. There's a workaround though - it's to always call user-defined class's method directly from built-in functions, so if you would call (new DateTime())->diff(new UserDefinedDateTime()) it would call UserDefinedDateTime#diff in the end which would need to implement the logic.

关于php - 我应该在我的 php 项目中使用 `DateTimeInterface` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37610078/

相关文章:

c# - 为什么条件语句需要强制转换?

generics - 编写比 Java 更优雅的 Copyable 接口(interface)

php - 表单提交后信息没有保存在mysql数据库中

php - 如何从 Laravel 的资源 Controller 中删除 show() 函数

PHP 递归目录迭代器 - 忽略某些文件。

python - Pandas 使用另一列的值移动日期

PHP DateTime::format 与 html 字符实体

php - Laravel 419 页面在生产服务器上已过期。 [框架: Laravel | version : 7. 5.2]

javascript - 将 MySql 日期时间戳转换为 JavaScript 日期格式

arrays - TypeScript 如何了解自定义数组类型中长度字段的行为?