查詢

DateTimeImmutable::createFromInterface()函式—用法及示例

「 從實現DateTimeInterface介面的物件建立一個不可變的DateTimeImmutable物件 」


函式名: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物件。

補充糾錯
熱門PHP函式
分享連結