最近,我发现有一个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
的类:
- https://github.com/php/php-src/pull/512
- https://www.mail-archive.com/internals@lists.php.net/msg79534.html
tl;dr core functions that accept
DateTime
andDateTimeImmutable
(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 callUserDefinedDateTime#diff
in the end which would need to implement the logic.
关于php - 我应该在我的 php 项目中使用 `DateTimeInterface` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37610078/