函式名: DateTime::createFromInterface()
適用版本: PHP 7.4.0 及以上版本
用法: DateTime::createFromInterface() 函式用於從實現了 DateTimeInterface 介面的物件中建立一個新的 DateTime 物件。
引數:
- interfaceObj: 必需。一個實現了 DateTimeInterface 介面的物件。
返回值: 成功時,返回一個新的 DateTime 物件,表示介面物件的日期和時間。如果出現錯誤,則返回 false。
示例:
// 建立一個實現 DateTimeInterface 介面的類
class CustomDate implements DateTimeInterface {
private $dateTime;
public function __construct($date) {
$this->dateTime = new DateTime($date);
}
public function format($format) {
return $this->dateTime->format($format);
}
// 其他 DateTimeInterface 介面方法的實現
}
// 建立 CustomDate 物件
$customDate = new CustomDate('2022-01-01');
// 透過 CustomDate 物件建立一個新的 DateTime 物件
$newDateTime = DateTime::createFromInterface($customDate);
// 輸出新的 DateTime 物件的日期和時間
echo $newDateTime->format('Y-m-d'); // 輸出: 2022-01-01
在上面的示例中,我們建立了一個自定義的類 CustomDate,它實現了 DateTimeInterface 介面。然後,我們建立了一個 CustomDate 物件並傳入日期 "2022-01-01"。最後,我們使用 DateTime::createFromInterface() 函式從 CustomDate 物件中建立一個新的 DateTime 物件,並透過 format() 方法輸出日期 "2022-01-01"。