函数名:DateTimeImmutable::createFromInterface()
适用版本:PHP 7.3.0+
用法及示例:
DateTimeImmutable::createFromInterface()函数用于从实现DateTimeInterface接口的对象创建一个不可变的DateTimeImmutable对象。DateTimeImmutable类是PHP的一个日期和时间处理类,它提供了一组用于操作、比较和格式化日期和时间的方法。
以下是函数的语法:
public static DateTimeImmutable DateTimeImmutable::createFromInterface(DateTimeInterface $object)
参数说明:
- $object:一个实现DateTimeInterface接口的对象。
返回值:
- 返回一个新的DateTimeImmutable对象,该对象代表与提供的$object相同的日期和时间。
示例:
class CustomDateTime implements DateTimeInterface {
private $timestamp;
public function __construct($timestamp) {
$this->timestamp = $timestamp;
}
public function getTimestamp() {
return $this->timestamp;
}
public function format($format) {
return date($format, $this->timestamp);
}
}
$customDateTime = new CustomDateTime(strtotime("2022-01-01"));
$dateTimeImmutable = DateTimeImmutable::createFromInterface($customDateTime);
echo $dateTimeImmutable->format("Y-m-d"); // 输出: 2022-01-01
在上面的示例中,我们自定义了一个实现了DateTimeInterface接口的类CustomDateTime。然后我们创建了一个$customDateTime对象,它具有一个代表2022-01-01的时间戳。接下来,我们使用DateTimeImmutable::createFromInterface()函数从$customDateTime对象创建了一个不可变的DateTimeImmutable对象$dateTimeImmutable。最后,我们用format()方法来格式化并输出该对象的日期。
需要注意的是,由于DateTimeImmutable::createFromInterface()函数返回一个不可变的对象,因此任何对$dateTimeImmutable对象的修改都不会影响原始的$customDateTime对象。