라이브러리

[PHP] DateTimeImmutable::createFromInterface - 지정된 DateTimeInterface 객체를 캡슐화하는 새 DateTimeImmutable 객체를 반환합니다.




DateTimeImmutable::createFromInterface


`DateTimeImmutable::createFromInterface`는 `DateTimeImmutable` 클래스의 정적 메서드로, `DateTimeInterface` 인터페이스를 구현한 객체를 사용하여 `DateTimeImmutable` 객체를 생성합니다. 이 메서드는 `DateTimeImmutable` 객체를 반환하며, 생성된 객체는 불변 객체이므로 수정할 수 없습니다.

사용법


`DateTimeImmutable::createFromInterface` 메서드를 사용하려면, `DateTimeInterface` 인터페이스를 구현한 객체를 생성하고, 이 객체를 `DateTimeImmutable::createFromInterface` 메서드에 전달하면 됩니다.

예제


#hostingforum.kr
php

// DateTimeInterface 인터페이스를 구현한 객체를 생성합니다.

class CustomDateTime implements DateTimeInterface

{

    private $year;

    private $month;

    private $day;



    public function __construct($year, $month, $day)

    {

        $this->year = $year;

        $this->month = $month;

        $this->day = $day;

    }



    public function format($format)

    {

        return sprintf('%04d-%02d-%02d', $this->year, $this->month, $this->day);

    }



    public function getTimestamp()

    {

        return mktime(0, 0, 0, $this->month, $this->day, $this->year);

    }



    public function getOffset()

    {

        return 0;

    }



    public function inInterval(DateTimeInterface $interval)

    {

        // 이 메서드는 구현하지 않습니다.

    }



    public function isDate()

    {

        return true;

    }



    public function isDateTime()

    {

        return true;

    }



    public function isInterval()

    {

        return false;

    }



    public function isMutable()

    {

        return false;

    }

}



// DateTimeImmutable::createFromInterface 메서드를 사용하여 DateTimeImmutable 객체를 생성합니다.

$customDateTime = new CustomDateTime(2022, 12, 25);

$dateTimeImmutable = DateTimeImmutable::createFromInterface($customDateTime);



// 생성된 DateTimeImmutable 객체를 출력합니다.

echo $dateTimeImmutable->format('Y-m-d H:i:s'); // 2022-12-25 00:00:00



참고


* `DateTimeImmutable` 클래스는 불변 객체를 반환하므로, 생성된 객체를 수정할 수 없습니다.
* `DateTimeInterface` 인터페이스는 `DateTime` 클래스와 `DateInterval` 클래스의 기능을 모두 구현해야 합니다.
* `DateTimeImmutable::createFromInterface` 메서드는 `DateTimeInterface` 인터페이스를 구현한 객체를 사용하여 `DateTimeImmutable` 객체를 생성합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 631 페이지

검색

게시물 검색